Flutter动作处理插件action_handler的使用

Flutter动作处理插件action_handler的使用

简单的方法来解耦视图与动作。

动作(Actions)

动作是指可以与用户交互但不是状态的东西。

示例1:在某些后端操作之后导航到另一个页面。后端结果不应该放在按钮的onPressed方法里(因为它不负责处理它),所以可以认为这是一个动作。

示例2:在某个非阻塞错误之后显示一个非阻塞错误对话框。如果有必要在某个非阻塞错误之后显示对话框,那么这个逻辑不应该放在按钮的onPressed方法里,所以这可能也是一个动作。

如何使用它

有两个可用的小部件:ActionHandlerValueListenableActionHandler

第一个使用Streams,第二个使用ValueNotifier。一旦你的Widget完成,你必须释放Stream/ValueNotifier。

ActionHandler<int>(
  actionInput: _controller.onStreamEvent,
  actionResult: (result) {
    print('Stream: $result \n');
  },
  child: Scaffold(
    appBar: AppBar(
      title: Text('Action Handler Demo'),
    ),
    body: Center(
      child: Text(
        'Push the button',
      ),
    ),
    floatingActionButton: FloatingActionButton(
      onPressed: _controller.increaseQuantity,
      tooltip: 'Increment',
      child: Icon(Icons.add),
    ),
  ),
),

示例代码

以下是完整的示例代码:

import 'package:action_handler/action_handler.dart';
import 'package:action_handler/value_listenable_action_handler.dart';
import 'package:example/main_controller.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) => MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: MyHomePage(
          controller: MainController(),
        ),
      );
}

class MyHomePage extends StatefulWidget {
  MyHomePage({
    required this.controller,
    Key? key,
  }) : super(key: key);

  final MainController controller;

  [@override](/user/override)
  State<StatefulWidget> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  MainController get _controller => widget.controller;

  [@override](/user/override)
  Widget build(BuildContext context) => ActionHandler<int>(
    actionInput: _controller.onStreamEvent,
    actionResult: (result) {
      print('Stream: $result \n');
    },
    child: ValueListenableActionHandler(
      actionInput: _controller.onNotifierEvent,
      actionResult: (result) {
        print('ValueNotifier: $result \n');
      },
      child: Scaffold(
        appBar: AppBar(
          title: Text('Action Handler Demo'),
        ),
        body: Center(
          child: Text(
            'Push the button',
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: _controller.increaseQuantity,
          tooltip: 'Increment',
          child: Icon(Icons.add),
        ),
      ),
    ),
  );

  [@override](/user/override)
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}

更多关于Flutter动作处理插件action_handler的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter动作处理插件action_handler的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


action_handler 是一个用于处理动作(Actions)的 Flutter 插件,它可以帮助你更好地管理和执行应用程序中的各种动作。通过 action_handler,你可以将动作的定义、执行和撤销等功能集中管理,从而简化代码结构并提高代码的可维护性。

安装 action_handler

首先,你需要在 pubspec.yaml 文件中添加 action_handler 依赖:

dependencies:
  flutter:
    sdk: flutter
  action_handler: ^1.0.0  # 请根据实际情况使用最新版本

然后运行 flutter pub get 来安装依赖。

基本用法

1. 定义一个动作

你可以通过继承 Action 类来定义一个动作。每个动作通常包含 executeundo 方法,分别用于执行和撤销动作。

import 'package:action_handler/action_handler.dart';

class MyAction extends Action {
  final String message;

  MyAction(this.message);

  @override
  Future<void> execute() async {
    print('Executing action: $message');
  }

  @override
  Future<void> undo() async {
    print('Undoing action: $message');
  }
}

2. 使用 ActionHandler 执行动作

ActionHandleraction_handler 的核心类,用于管理和执行动作。

import 'package:flutter/material.dart';
import 'package:action_handler/action_handler.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Action Handler Example')),
        body: Center(
          child: ElevatedButton(
            onPressed: () async {
              var action = MyAction('Hello, ActionHandler!');
              await ActionHandler().execute(action);
            },
            child: Text('Execute Action'),
          ),
        ),
      ),
    );
  }
}

高级用法

1. 撤销和重做

ActionHandler 提供了撤销和重做功能。你可以通过调用 undoredo 方法来撤销或重做最近的动作。

await ActionHandler().undo();  // 撤销最近的动作
await ActionHandler().redo();  // 重做最近撤销的动作

2. 批量执行动作

你可以使用 BatchAction 来批量执行多个动作。

var action1 = MyAction('Action 1');
var action2 = MyAction('Action 2');

var batchAction = BatchAction([action1, action2]);
await ActionHandler().execute(batchAction);

3. 监听动作执行状态

你可以通过 ActionHandler 提供的 onActionExecutedonActionUndone 来监听动作的执行和撤销状态。

ActionHandler().onActionExecuted.listen((action) {
  print('Action executed: $action');
});

ActionHandler().onActionUndone.listen((action) {
  print('Action undone: $action');
});
回到顶部