Flutter状态管理2

在前面的文章中我们学习了如何使用Provider来实现状态管理,本次就来介绍下如何使用Scoped和flutter_redux进行状态管理。

Scoped_model

在前面的文章中我们了解到Provider其实是借助于InheritedWidget与Listenable实现的状态管理,Scoped_model呢其实也是这样实现的,只不过 Scoped_model使用AnimatedBuilder实现数据接收并通过ScopedModelDescendant做了层封装,而Provider没有借助于Widget。

我们还是按照上篇文章的例子来进行讲解。

惯例第三方库我们需要在pubspec.yaml中进行声明

scoped_model: ^1.0.1

然后调用pub get

首先我们定义数据存储的model,这次我们需要继承Model,这个Model是Scoped_model中的封装类,其实也是继承Listenable

class UserModel extends Model {
  String _nickName = "userName";

  // 读方法
  String get nickName => _nickName;

  // 写方法
  void updateNickName(String nickName) {
    _nickName = nickName;
    notifyListeners(); // 通知听众刷新
  }
}

然后我们需要在合适的地方初始化UserModel,这次我们在app的入口来初始化它

void main() {
  runApp(new MaterialApp(
    home: MyApp(model: UserModel(),),
  ));
}

然后使用ScopedModel(ScopedModel其实是一个继承与StatelessWidget的Widget)来构建Wdiget,具体实现原理也很简单,大家可以去看下源码。

class MyApp extends StatelessWidget {
  final UserModel model;

  const MyApp({Key key, @required this.model}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ScopedModel<UserModel>(//构建Widget
      model: model,
      child: MaterialApp(
        title: 'Scoped Model Demo',
        home: HomePage(),
      ),
    );
  }
}

最后我们在需要使用数的地方使用ScopedModelDescendant来构建Wdiget并获取到相应的Model

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("scopedTitle"),
      ),
      body: Center(
        child: Column(
          children: [
            ScopedModelDescendant<UserModel>(//构建Wdiget并传递Model
              builder: (context, child, model) {
                return Text(
                  model.nickName,
                  style: Theme.of(context).textTheme.display1,
                );
              },
            ),
            RaisedButton(
              child: Text("去设置界面"),
              onPressed: () {
                Navigator.push(context, MaterialPageRoute(builder: (context) {
                  return SecondPage();
                }));
              },
            )
          ],
        ),
      ),
    );
  }
}

第二个界面

class SecondPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    TextEditingController _unameController = TextEditingController();

    return Scaffold(
      appBar: AppBar(
        title: Text("ProviderTitle"),
      ),
      body: Column(
        children: [
          TextField(
            autofocus: true,
            controller: _unameController,
            decoration: InputDecoration(
                labelText: "用户名",
                hintText: "用户名或邮箱",
                prefixIcon: Icon(Icons.person)),
          ),
          ScopedModelDescendant<UserModel>(//构建Wdiget并传递Model
            builder: (context, child, model) {
              return RaisedButton(
                onPressed: () {
                  model.updateNickName(_unameController.text);
                },
                child: Text("设置"),
              );
            },
          ),
        ],
      ),
    );
  }
}
Flutter状态管理2_post1

ScopedModel使用起来非常的简单,接下来我们来看下flutter_redux如何使用。

flutter_redux

Redux是一种单向数据流架构,往往作用于前端页面当中,在Flutter我们同样可以使用Redux来进行状态管理

image

我们在Redux中,所有的状态都储存在Store里。这个Store会放在App顶层。

View拿到Store储存的状态(State)并把它映射成视图。View还会与用户进行交互,用户点击按钮滑动屏幕等等,这时会因为交互需要数据发生改变。

Redux让我们不能让View直接操作数据,而是通过发起一个action来告诉Reducer,状态得改变啦。

这时候Reducer接收到了这个action,他就回去遍历action表,然后找到那个匹配的action,根据action生成新的状态并把新的状态放到Store中。

Store丢弃了老的状态对象,储存了新的状态对象后,就通知所有使用到了这个状态的View更新(类似setState)。这样我们就能够同步不同view中的状态了。

接下来我们看下如何使用Redux

首先引入第三方库

flutter_redux: ^0.6.0
redux: ">=4.0.0 <5.0.0"

首先我们建立基础类

enum Actions { UserState }//枚举类,声明操作

class ActionType {//定义基类
  String type;
  ActionType(this.type);
}

class UserState extends ActionType {//定义操作类
  String userName;
  UserState({this.userName}) : super('userName');
}

根据传入的类型进行业务处理

UserState counterReducer(UserState state, dynamic action) {

  if ("userName"==( action as UserState).type) {
    return action;
  }
}

在根结点初始化Redux

void main() {
  final store = Store<UserState>(counterReducer,
      initialState: UserState(userName: "userName"));

  runApp(FlutterReduxApp(
    store: store,
  ));
}

class FlutterReduxApp extends StatelessWidget {
  final Store<UserState> store;

  FlutterReduxApp({Key key, this.store}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return StoreProvider<UserState>(
      store: store,
      child: MaterialApp(

        title: "Flutter Redux Demo",
        routes: { "/SecondPage": (context) => SecondPage()},
        home: HomePage(),
      ),
    );
  }
}

第一个界面使用StoreConnector监听数据变更

class HomePage extends StatelessWidget {


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("scopedTitle"),
      ),
      body: Center(
        child: Column(
          children: [
            StoreConnector<UserState, String>(
              converter: (store) => store.state.userName,
              builder: (context, userName) {
                return Text(
                  userName,
                  style: Theme
                      .of(context)
                      .textTheme
                      .display1,
                );
              },
            ),
            RaisedButton(
              child: Text("去设置界面"),
              onPressed: () {
                Navigator.pushNamed(context, "/SecondPage");
              },
            )
          ],
        ),
      ),

    );
  }
}

第二个界面,使用store.dispatch()发送事件

class SecondPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    TextEditingController _unameController = TextEditingController();

    return Scaffold(
      appBar: AppBar(
        title: Text("ProviderTitle"),
      ),
      body: Column(
        children: [
          TextField(
            autofocus: true,
            controller: _unameController,
            decoration: InputDecoration(
                labelText: "用户名",
                hintText: "用户名或邮箱",
                prefixIcon: Icon(Icons.person)),
          ),
          StoreConnector<UserState, VoidCallback>(
            converter: (store) {
              return () =>
                  store.dispatch(UserState(userName: _unameController.text));
            },
            builder: (store, callback) {
              return RaisedButton(
                onPressed: callback,
                child: Text("设置"),
              );
            },
          ),
        ],
      ),
    );
  }
}
image

Redux使用起来相对的麻烦,但是面对复杂的业务逻辑使用Redux就会体现出他的价值。

小结

  1. Scoped_model使用InheritedWidget和Listenable实现监听和数据传递
  2. Redux的用法跟react里的用法类似
  3. Redux虽然不是最佳的解决方案,但是面对复杂的界面就会突出它的特点

关注Flutter开发者获取更多文章


image
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,084评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,623评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,450评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,322评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,370评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,274评论 1 300
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,126评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,980评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,414评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,599评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,773评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,470评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,080评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,713评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,852评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,865评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,689评论 2 354