Token导航 LogoToken导航TokenDH.com
开发external-servicegithub未标认证来源可访问许可证需确认审计通过

flutter-managing-stateFlutter managing state 命令行

Agent Skill

flutter-managing-state 用于记录任务执行中的错误、用户纠正、经验和能力缺口,适合在 Codex、Claude、Cursor、Gemini CLI 中希望让 Agent 持续沉淀问题、修正和最佳实践时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

230,664

周安装

9,554

GitHub Stars

1,313

下载量

77,038
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:flutter-managing-state(Flutter managing state 命令行)
来源仓库:https://github.com/flutter/skills
仓库路径:skills/flutter-managing-state
安装命令:
npx skills add https://github.com/flutter/skills --skill flutter-managing-state
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/flutter/skills --skill flutter-managing-state

简介

使用 StatefulWidget、MVVM 和 Provider 管理 Flutter 中的临时状态和应用程序级状态。

  • 区分短暂状态(单个小部件,使用 setState() 管理))和应用程序状态(跨小部件共享,由 MVVM 和提供程序管理
  • 包)
  • 使用单一事实来源实现单向数据流:模型处理数据,ViewModel 通过 ChangeNotifier 管理 UI 状态, 查看消费和显示状态
  • 为 MVVM 实现提供顺序工作流程:定义存储库、创建 ViewModel、通过 ChangeNotifierProvider 注入,用Consumer消费状态
  • 或 context.read()
  • 包括短暂状态模式和具有异步操作、加载状态和错误处理的应用程序状态管理的完整代码示例

SKILL.md

Managing State in Flutter

Contents

Core Concepts

Flutter's UI is declarative; it is built to reflect the current state of the app (UI = f(state)). When state changes, trigger a rebuild of the UI that depends on that state.

Distinguish between two primary types of state to determine your management strategy:

  • Ephemeral State (Local State): State contained neatly within a single widget (e.g., current page in a PageView, current selected tab, animation progress). Manage this using a StatefulWidget and setState().
  • App State (Shared State): State shared across multiple parts of the app and maintained between user sessions (e.g., user preferences, login info, shopping cart contents). Manage this using advanced approaches like InheritedWidget, the provider package, and the MVVM architecture.

Architecture and Data Flow

Implement the Model-View-ViewModel (MVVM) design pattern combined with Unidirectional Data Flow (UDF) for scalable app state management.

  • Unidirectional Data Flow (UDF): Enforce a strict flow where state flows *down* from the data layer, through the logic layer, to the UI layer. Events from user interactions flow *up* from the UI layer, to the logic layer, to the data layer.
  • Single Source of Truth (SSOT): Ensure data changes always happen in the data layer (Repositories). The SSOT class must be the only class capable of modifying its respective data.
  • Model (Data Layer): Handle low-level tasks like HTTP requests, data caching, and system resources using Repository classes.
  • ViewModel (Logic Layer): Manage the UI state. Convert app data from the Model into UI State. Extend ChangeNotifier and call notifyListeners() to trigger UI rebuilds when data changes.
  • View (UI Layer): Display the state provided by the ViewModel. Keep views lean; they should contain minimal logic (only routing, animations, or simple UI conditionals).

Workflow: Selecting a State Management Approach

Evaluate the scope of the state to determine the correct implementation strategy.

  • If managing Ephemeral State (single widget scope):

1. Subclass StatefulWidget and State. 2. Store mutable state as private fields within the State class. 3. Mutate state exclusively inside a setState() callback to mark the widget as dirty and schedule a rebuild.

  • If managing App State (shared across widgets):

1. Implement the MVVM pattern. 2. Use the provider package (a wrapper around InheritedWidget) to inject state into the widget tree. 3. Use ChangeNotifier to emit state updates.

Workflow: Implementing MVVM with Provider

Follow this sequential workflow to implement app-level state management using MVVM and provider.

Task Progress:

  • 1. Define the Model (Repository).
  • 2. Create the ViewModel (ChangeNotifier).
  • 3. Inject the ViewModel into the Widget Tree.
  • 4. Consume the State in the View.
  • 5. Validate the implementation.

1. Define the Model (Repository)

Create a repository class to act as the Single Source of Truth (SSOT) for the specific data domain. Handle all external API calls or database queries here.

2. Create the ViewModel (ChangeNotifier)

Create a ViewModel class that extends ChangeNotifier.

  • Pass the Repository into the ViewModel via dependency injection.
  • Define properties for the UI state (e.g., isLoading, data, errorMessage).
  • Implement methods to handle UI events. Inside these methods, mutate the state and call notifyListeners() to trigger UI rebuilds.

3. Inject the ViewModel into the Widget Tree

Use ChangeNotifierProvider from the provider package to provide the ViewModel to the widget subtree that requires it. Place the provider as low in the widget tree as possible to avoid polluting the scope.

4. Consume the State in the View

Access the ViewModel in your StatelessWidget or StatefulWidget.

  • Use Consumer<MyViewModel> to rebuild specific parts of the UI when notifyListeners() is called.
  • Use context.read<MyViewModel>() (or Provider.of<MyViewModel>(context, listen: false)) inside event handlers (like onPressed) to call ViewModel methods without triggering a rebuild of the calling widget.

5. Validate the implementation

Run the following feedback loop to ensure data flows correctly:

  1. Trigger a user action in the View.
  2. Verify the ViewModel receives the event and calls the Repository.
  3. Verify the Repository updates the SSOT and returns data.
  4. Verify the ViewModel updates its state and calls notifyListeners().
  5. Verify the View rebuilds with the new state. *Run validator -> review errors -> fix missing notifyListeners() calls or incorrect Provider scopes.*

Examples

Ephemeral State Implementation (setState)

Use this pattern strictly for local, UI-only state.

class EphemeralCounter extends StatefulWidget {
  const EphemeralCounter({super.key});

  @override
  State<EphemeralCounter> createState() => _EphemeralCounterState();
}

class _EphemeralCounterState extends State<EphemeralCounter> {
  int _counter = 0; // Local state

  void _increment() {
    setState(() {
      _counter++; // Mutate state and schedule rebuild
    });
  }

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: _increment,
      child: Text('Count: $_counter'),
    );
  }
}

App State Implementation (MVVM + Provider)

Use this pattern for shared data and complex business logic.

// 1. Model (Repository)
class CartRepository {
  Future<void> saveItemToCart(String item) async {
    // Simulate network/database call
    await Future.delayed(const Duration(milliseconds: 500));
  }
}

// 2. ViewModel (ChangeNotifier)
class CartViewModel extends ChangeNotifier {
  final CartRepository repository;

  CartViewModel({required this.repository});

  final List<String> _items = [];
  bool isLoading = false;
  String? errorMessage;

  List<String> get items => List.unmodifiable(_items);

  Future<void> addItem(String item) async {
    isLoading = true;
    errorMessage = null;
    notifyListeners(); // Trigger loading UI

    try {
      await repository.saveItemToCart(item);
      _items.add(item);
    } catch (e) {
      errorMessage = 'Failed to add item';
    } finally {
      isLoading = false;
      notifyListeners(); // Trigger success/error UI
    }
  }
}

// 3. Injection & 4. View (UI)
class CartApp extends StatelessWidget {
  const CartApp({super.key});

  @override
  Widget build(BuildContext context) {
    // Inject ViewModel
    return ChangeNotifierProvider(
      create: (_) => CartViewModel(repository: CartRepository()),
      child: const CartScreen(),
    );
  }
}

class CartScreen extends StatelessWidget {
  const CartScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Consumer<CartViewModel>(
        builder: (context, viewModel, child) {
          if (viewModel.isLoading) {
            return const CircularProgressIndicator();
          }
          if (viewModel.errorMessage != null) {
            return Text(viewModel.errorMessage!);
          }
          return ListView.builder(
            itemCount: viewModel.items.length,
            itemBuilder: (_, index) => Text(viewModel.items[index]),
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        // Use read() to access methods without listening for rebuilds
        onPressed: () => context.read<CartViewModel>().addItem('New Item'),
        child: const Icon(Icons.add),
      ),
    );
  }
}

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Claude

33.58%
按下载量换算25,869

Codex

32.88%
按下载量换算25,330

Cursor

17.95%
按下载量换算13,828

Gemini CLI

10.36%
按下载量换算7,981

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

external-service

该 Skill 可能调用第三方服务、云服务或外部模型 API,使用前需要确认账号、额度、数据发送范围和服务条款。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills