状态管理

解决的问题是数据传递的问题,没有用Provider,那么子组件要收到父组件的参数,只能一层一层传递,如果组件过多,传递很麻烦,于是就产生了很多状态管理,今天我们就说说谷歌推出的Provider.

怎么理解这个状态管理呢?

要传递的参数就是你的快递,父组件就是快递小哥,子组件就是你自己

传统的就是快递小哥,一层一层楼爬,送到你的手上。 Provider呢,就是快递小哥直接给前台的小姐姐,然后小姐姐发通知告诉你,有你的快递,你就愉快的去找小姐姐了。

Provider声明

class Counter with ChangeNotifier {
  int _count = 0;

  int get count => _count;

  incrementCounter() {
    _count = _count + 1;
    notifyListeners();
  }
}

调用方

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    //声明Provider需要一个MultiProvider,里面是数组类型,可以放多个Provider
    return MultiProvider(
        providers: [
          ChangeNotifierProvider(
            create: (_) => Counter(),
          )
        ],
        child: MaterialApp(
            title: 'Flutter Demo',
            theme: ThemeData(
              primarySwatch: Colors.blue,
            ),
            home: MyHomePage(title: 'Flutter Demo Home Page')));
  }
}

class MyHomePage extends StatelessWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Container(
          child: TabBar(
            tabs: <Widget>[
              Tab(
                child: Text("首页"),
              ),
            ],
          ),
        ),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            //获取Provider中的值
            Consumer<Counter>(builder: (context, data, _) {
              return Text(
                '${data.count}',
                style: Theme.of(context).textTheme.display1,
              );
            }),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          //此处是要调用更新数据的方法
          Counter counter = Provider.of<Counter>(context);
          counter.incrementCounter();
        },
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}