Flutter: 使用Provider进行状态管理

谷歌2019开发者大会上推荐使用provider进行flutter开发。(注:provider类以于angular的依赖注入用于数据交互和组件间数据传递和状态变更)。
使用命令flutter create myapp创建一个名为myapp的flutter项目文件
在pubspec.yaml里加入三方插件:

provider:

粘贴以下代码覆盖main.dart自动生成的代码:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

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

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    int _counter = 0;
    return Scaffold(
      appBar: AppBar(
        title: Text("Provider Demo"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          FloatingActionButton(
            onPressed: () {},
            tooltip: 'Increment',
            child: Icon(Icons.add),
          ),
          SizedBox(height: 10),
          FloatingActionButton(
            onPressed: () {},
            tooltip: 'Increment',
            child: Icon(Icons.remove),
          )
        ],
      ),
    );
  }
}

创建一个Counter包含increment和decrement两个方法的封装类。


import 'package:flutter/material.dart';

class Counter with ChangeNotifier {
  int _counter;

  Counter(this._counter);

  getCounter() => _counter;
  setCounter(int counter) => _counter = counter;

  void increment() {
    _counter++;
    notifyListeners();
  }

  void decrement() {
    _counter--;
    notifyListeners();
  }
}

通过with关键字生成一个ChangeNotifier的混合类。该类用来为counter类创建侦听,并通过在Increment和decrement方法里notifyListeners();方法被调用。
可以通过Counter类的实例化来调用其中的方法,在代码中的HomePage组件中使用Counter类方法是:material app中homepage组件外使用ChangeNotifierProvider进行封装。

home: ChangeNotifierProvider<Counter>(
    create: (_) => Counter(0), //原文的builder被create取代
    child: HomePage(),
)

实例化ChangeNotifierProvider并使用<>把Counter类做为组件传递到child中。

访问对象

现在可以通过Provider.of<Object>(context)或Consumer两种组件访问Counter对象参数或方法。现在使用第一种方式,另外一种Consumer方式链接

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final counter = Provider.of<Counter>(context);
    return Scaffold(
      appBar: AppBar(
        title: Text("Provider Demo"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '${counter.getCounter()}',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          FloatingActionButton(
            onPressed: counter.increment,
            tooltip: 'Increment',
            child: Icon(Icons.add),
          ),
          SizedBox(height: 10),
          FloatingActionButton(
            onPressed: counter.decrement,
            tooltip: 'Increment',
            child: Icon(Icons.remove),
          )
        ],
      ),
    );
  }
}

结论

这个简单的示例也就是了解provider设计模式的皮毛,并不能解决项目中的所有问题,比如StreamProvider用来代替rxdart和streams。哪怕是前端复杂起来也超出想象,所以还得脚踏实地的学下去。
原文链接

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。