Flutter状态管理插件states的使用

发布于 1周前 作者 phonegap100 来自 Flutter

Flutter状态管理插件states的使用

API

abstract class IStates {
  String get current;
  bool get locked;
  List<StatesTransition> get all;
  
  List<StatesTransition> actions({String from});
  List<StatesMeta> metas({String from});
  
  StatesMeta add( String state );
  StatesTransition when({
    String at,
    String to,
    String on,
    StatesTransitionFunction handler
  });
  
  String subscribe(StatesTransitionFunction listener);
  bool unsubscribe(String subscriptionKey);
  
  bool change({ String to, bool run = true });
  bool has({
    String action,
    String state,
    bool conform = true
  });
  StatesTransition get( String action );
  bool execute( String action );
  bool on(String action, StatesTransitionHandler listener);
  
  void reset();
  void dispose();
  
  void lock({@required String key});
  void unlock({@required String key});
}

使用

一个简单的使用示例

States states = new States();

states.add(STATE_INITIAL);

states.add(STATE_LOADING);
states.add(STATE_LOADING_COMPLETE);
states.add(STATE_LOADING_FAILED);

states.when(
  at: STATE_INITIAL,
  to: STATE_LOADING,
  on: ACTION_LOADING_START,
  execute: (StatesTransition action) {
    print("> CURRENT on ACTION_LOADING_START state: " + states.current);
    scheduleMicrotask(() {
      print("> \t END OF microtask queue -> state: " + states.current);
      var nextBool = Random.secure().nextBool();
      print("> \t\t next bool: " + nextBool.toString());
      states.run(nextBool ? ACTION_LOADING_COMPLETE : ACTION_LOADING_FAILED);
    });
  });

states.when(
  at: STATE_LOADING,
  to: STATE_LOADING_COMPLETE,
  on: ACTION_LOADING_COMPLETE,
  execute: (StatesTransition action) {
    print("> CURRENT on ACTION_LOADING_COMPLETE - state: " + states.current);
    scheduleMicrotask(() => print("> \t END OF microtask queue -> state: " + states.current));
  }
);

states.when(
  at: STATE_LOADING,
  to: STATE_LOADING_FAILED,
  on: ACTION_LOADING_FAILED,
  execute: (StatesTransition action) {
    print("> CURRENT on ACTION_LOADING_FAILED state: " + states.current);
    scheduleMicrotask(() => print("> \t END OF microtask queue -> state: " + states.current));
  }
);

states.run(ACTION_LOADING_START);

单页应用(SPA)与States结合使用

请查看如何使用此库帮助创建带有简单dart:html的单页应用。 查看文件夹 example/spa_with_states SPA with States

示例代码

1. 简单加载FMS

输出:

> BEFORE LOADING START -> state: state_initial
> RUN -> ACTION_LOADING_START
> CURRENT -> ACTION_LOADING_START 
    state: state_initial 
    transition:  [state_initial] -> [state_loading] on: [action_start_loading]
>     END OF microtask queue -> state: state_loading next action: action_loading_complete
> CURRENT -> ACTION_LOADING_COMPLETE 
    state: state_loading 
    transition:  [state_loading] -> [state_loading_complete] on: [action_loading_complete]
>     END OF microtask queue -> state: state_loading_complete

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

1 回复

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


在Flutter中,状态管理是一个核心概念,特别是在构建复杂应用时。provider包中的ChangeNotifierChangeNotifierProvider是常用的状态管理解决方案之一。尽管你提到的“states”可能是一个泛指,但我会基于provider包来展示一个具体的代码案例,这是Flutter社区中非常流行的一种状态管理方式。

以下是一个使用ChangeNotifierChangeNotifierProvider进行状态管理的简单示例:

1. 创建一个ChangeNotifier类

首先,我们需要创建一个继承自ChangeNotifier的类,用于管理状态。

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

class Counter with ChangeNotifier {
  int _count = 0;

  int get count => _count;

  void increment() {
    _count++;
    notifyListeners(); // 通知监听者状态已改变
  }
}

2. 使用ChangeNotifierProvider包装MaterialApp

接下来,我们在MaterialApp外层使用ChangeNotifierProvider来提供Counter实例。

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'counter.dart'; // 假设上面的代码保存在counter.dart文件中

void main() {
  runApp(
    ChangeNotifierProvider(
      create: (_) => Counter(),
      child: MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

3. 在UI组件中消费状态

最后,在需要访问和修改状态的UI组件中,使用ConsumerProvider.of来访问Counter实例。

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

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Demo Home Page'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '${Provider.of<Counter>(context).count}',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Provider.of<Counter>(context, listen: false).increment();
        },
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

在这个例子中,Provider.of<Counter>(context)用于获取Counter实例,而listen: false参数在调用increment方法时指定,因为我们只是修改状态而不是监听它(监听是在Text组件中自动发生的,当状态改变时,Text组件会重建以显示新的值)。

替代方案:使用Consumer

作为替代,你可以使用Consumer来更简洁地访问和监听状态:

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

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Demo Home Page'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('You have pushed the button this many times:'),
            Consumer<Counter>(
              builder: (context, counter, child) => Text(
                '${counter.count}',
                style: Theme.of(context).textTheme.headline4,
              ),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Consumer<Counter>(
            builder: (context, counter, child) => counter.increment(),
            child: Container(), // 这里需要一个非空的child,但不会被渲染
          );
        },
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

注意,在FloatingActionButtononPressed中,我们使用了Consumer来调用increment方法,虽然这里更常见的做法是使用Provider.of<Counter>(context, listen: false).increment();,因为Consumer通常用于构建UI组件,而不是执行无UI影响的状态更新。

以上代码展示了如何在Flutter中使用provider包进行状态管理,希望这能帮助你理解如何在Flutter应用中实施状态管理。

回到顶部