搜索插件、代码仓与 APP 分类

插件详情v9.5.2

command_it

command_it 是一种基于 `ValueListenable` 和命令设计模式来管理状态的方法。它是 flutter_command 的重新命名版本。

AndroidiOSWebmacOSWindowsLinux
近 30 天下载
5010
喜欢数
35
Pub 分数
160

安装插件

flutter pub add command_it

插件介绍

基于插件公开信息、社区数据与项目使用情况整理的选型参考。

command_it 是一个基于 `ValueListenable` 和命令设计模式的状态管理解决方案,为 Flutter 应用提供了一种简洁的响应式方式来处理状态变化。最初名为 flutter_command,它提供了一种结构化的方法来管理异步操作和状态更新。该包通过将操作封装在命令中,促进了关注点分离,使代码更易于测试和维护。它与 Flutter 的响应式框架无缝集成,并支持所有主要平台。

适合场景

  • 管理异步操作,如 API 调用
  • 处理表单提交
  • 实现撤销/重做功能
  • 在多个小部件之间协调状态变化
  • 构建可重用的业务逻辑层

主要特点

  • 通过 ValueListenable 实现响应式状态
  • 命令模式用于封装操作
  • 内置对加载、错误和成功状态的支持
  • 与 Flutter 的 widget 树轻松集成
  • 跨平台兼容性

适合对象

  • 寻求轻量级状态管理替代方案的开发者
  • 希望在用户界面和业务逻辑之间实现清晰分离的团队
  • 需要可预测状态转换的项目
  • 频繁执行异步操作的应用程序
  • 测试驱动开发工作流程

使用建议

  • 对于不熟悉命令模式的新用户,可能需要一定的学习曲线
  • 不太适合非常简单的状态需求
  • 与更大的状态管理解决方案相比,生态系统有限
  • 最佳搭配其他工具以实现完整的应用架构

原始 README

以下为关联源码仓库的 README 原文快照,最新内容请访问源码仓库。

command_it logo
Buy Me A Coffee
Sponsor

command_it codecov

📚 Complete documentation available at flutter-it.dev Check out the comprehensive docs with detailed guides, examples, and best practices!


🔄 Migration Notice (v9.0.0)

Important: Version 9.0.0 introduces new, clearer API naming. The old API is deprecated and will be removed in v10.0.0.

Quick Migration: execute() → run() | isExecuting → isRunning | canExecute → canRun

Run dart fix --apply to automatically update most usages.

Complete migration guide →


Command pattern for Flutter - wrap functions as observable objects with automatic state management

Commands replace async methods with reactive alternatives. Wrap your functions, get automatic loading states, error handling, and UI integration. No manual state tracking, no try/catch everywhere.

Call them like functions. React to their state. Simple as that.

Part of flutter_it — A construction set of independent packages. command_it works standalone or combines with watch_it for reactive UI updates.

Why Commands?

  • 🎯 Declarative — Wrap functions, get observable execution state automatically
  • ⚡ Automatic State — isRunning, value, errors tracked without manual code
  • 🛡️ Smart Error Handling — Route errors globally/locally with filters
  • 🔒 Built-in Protection — Prevents parallel execution automatically
  • 🎛️ Restrictions — Disable commands conditionally (auth, network, etc.)
  • 🧪 Testable — Easier to test than traditional async methods

Learn more about the benefits →

Quick Start

Installation

Add to your pubspec.yaml:

dependencies:
  command_it: ^9.0.2
  listen_it: ^5.3.3  # Required - commands build on ValueListenable
Basic Example
import 'package:command_it/command_it.dart';

// 1. Create a command that wraps your async function
class CounterManager {
  int _counter = 0;

  late final incrementCommand = Command.createAsyncNoParam<String>(
    () async {
      await Future.delayed(Duration(milliseconds: 500));
      _counter++;
      return _counter.toString();
    },
    initialValue: '0',
  );
}

// 2. Use it in your UI - command is a ValueListenable
class CounterWidget extends StatelessWidget {
  final manager = CounterManager();

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        // Shows loading indicator automatically while command runs
        ValueListenableBuilder<bool>(
          valueListenable: manager.incrementCommand.isRunning,
          builder: (context, isRunning, _) {
            if (isRunning) return CircularProgressIndicator();

            return ValueListenableBuilder<String>(
              valueListenable: manager.incrementCommand,
              builder: (context, value, _) => Text('Count: $value'),
            );
          },
        ),
        ElevatedButton(
          onPressed: manager.incrementCommand.run,
          child: Text('Increment'),
        ),
      ],
    );
  }
}

That's it! The command automatically:

  • Prevents parallel execution
  • Tracks isRunning state
  • Publishes results
  • Handles errors

Full tutorial

Using CommandBuilder

Simplify your UI code with the built-in builder widget:

CommandBuilder<void, String>(
  command: manager.incrementCommand,
  whileRunning: (context, _, __) => CircularProgressIndicator(),
  onData: (context, value, _) => Text('Count: $value'),
  onError: (context, error, _, __) => Text('Error: $error'),
)

Key Features

Command Types

Create commands for any function signature:

Command Properties

Observe different aspects of execution:

  • value — Last successful result
  • isRunning — Async execution state
  • isRunningSync — Synchronous version for restrictions
  • canRun — Combined restriction and running state
  • errors — Stream of errors
  • results — CommandResult with all data at once
Error Handling

Declarative error routing with filters:

Advanced Features
Piping Commands

Chain commands together with the pipeToCommand() extension. When the source completes successfully, it automatically triggers the target command:

// Trigger refresh after save completes
saveCommand.pipeToCommand(refreshCommand);

// Transform result before passing to target
userIdCommand.pipeToCommand(fetchUserCommand, transform: (id) => UserRequest(id));

// Pipe from any ValueListenable - track execution state changes
longRunningCommand.isRunning.pipeToCommand(spinnerStateCommand);

The pipeToCommand() extension works on any ValueListenable, including commands, isRunning, results, or plain ValueNotifier. Returns a ListenableSubscription for manual cancellation if needed.

⚠️ Warning: Circular pipes (A→B→A) cause infinite loops. Ensure your pipe graph is acyclic.

Ecosystem Integration

Built on listen_it — Commands are ValueListenable objects, so they work with all listen_it operators (map, debounce, where, etc.).

// Register with get_it
di.registerLazySingleton(() => TodoManager());

// Use commands in your managers
class TodoManager {
  final loadTodosCommand = Command.createAsyncNoParam<List<Todo>>(
    () => api.fetchTodos(),
    [],
  );

  // Debounce search with listen_it operators
  final searchCommand = Command.createSync<String, String>((s) => s, '');

  TodoManager() {
    searchCommand.debounce(Duration(milliseconds: 500)).listen((term, _) {
      loadTodosCommand.run();
    });
  }
}

Want more? Combine with other flutter_it packages:

  • listen_it — Required dependency. ValueListenable operators and reactive collections.

  • Optional: watch_it — State management. Watch commands reactively without builders: watchValue((m) => m.loadCommand).

  • Optional: get_it — Service locator for dependency injection. Access managers with commands from anywhere: di<TodoManager>().

💡 flutter_it is a construction set — command_it works standalone. Add watch_it and get_it when you need reactive UI and dependency injection.

Explore the ecosystem →

AI-Assisted Development

This package ships an Agent Skill for AI coding assistants (Claude Code, Cursor, GitHub Copilot, Codex, Gemini CLI and others) in skills/command-it-expert/. It teaches them the critical rules, common patterns and anti-patterns of command_it. Install it into your project with the official Dart skills tool:

dart run skills@ get

For the ecosystem-wide skills (architecture guidance, feed/data-source patterns, overview) and the skills of the other flutter_it packages run:

dart run skills@ add flutter-it/flutter_it

Learn more about AI skills →

Learn More

📖 Documentation
💬 Community & Support

Contributing

Contributions are welcome! Please read the contributing guidelines before submitting PRs.

License

MIT License - see LICENSE file for details.


Part of the flutter_it ecosystem — Build reactive Flutter apps the easy way. No codegen, no boilerplate, just code.

所属分类

依赖

依赖清单 3 项

源码仓库

使用此插件的项目