🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
## 推荐阅读 [《Flutter实战》7.2 数据共享(InheritedWidget)](https://book.flutterchina.club/chapter7/inherited_widget.html) [Flutter知识点: InheritedWidget](https://www.jianshu.com/p/387e2454d590) [Flutter状态管理(1)——InheritedWidget](https://cloud.tencent.com/developer/article/1506834) ## 状态管理 Flutter的状态管理分为两种:局部状态和全局状态。 * 局部状态:就是一个StatefulWidget可以搞定的;其他Widget不需要知道你的状态,你也不需要依赖其他Widget的状态 * 全局状态:整个app很多页面都需要用到的状态,比如是否登录了,用户名、用户id等; Flutter状态管理系列主要指的是全局状态的管理,主要介绍的几种实现方式有: * InheritedWidget * StreamBuilder * Provider 简单来说,InheritedWidget下面的Widget都可以获取到该Widget持有的状态。 Theme这个源码大家可以去看一下 ,对理解 InheritedWidget会有比较大的帮助 ## Demo ~~~ import 'package:flutter/material.dart'; class InheritedOneData{ int number = 1; @override bool operator ==(other) { return number == (other as InheritedOneData).number; } } class InheritedWidgetOne extends InheritedWidget { final InheritedOneData data; InheritedWidgetOne({@required this.data, Widget child}) : super(child: child); static InheritedWidgetOne of(BuildContext context) { return context.inheritFromWidgetOfExactType(InheritedWidgetOne); } @override bool updateShouldNotify(InheritedWidgetOne oldWidget) { return oldWidget.data != data; } } class InheritedWidgetDemo extends StatelessWidget { @override Widget build(BuildContext context) { Scaffold scaffold = Scaffold( appBar: AppBar( title: new Text("ScrollDemoPage"), ), body: new Container( child: new ContentView(), ), ); return new InheritedWidgetOne( data: new InheritedOneData(), child: scaffold, ); } } class ContentView extends StatelessWidget { @override Widget build(BuildContext context) { return new Column( children: <Widget>[ new ShowView(), new AddView(), ], ); } } class ShowView extends StatelessWidget { @override Widget build(BuildContext context) { InheritedOneData data = InheritedWidgetOne.of(context).data; return new Text("${data.number}"); } } class AddView extends StatefulWidget { @override State<AddView> createState() { return new AddViewViewState(); } } class AddViewViewState extends State<AddView> { @override Widget build(BuildContext context) { return new RaisedButton(onPressed: () { setState(() { InheritedOneData data = InheritedWidgetOne.of(context).data; data.number ++ ; }); }, child: Text("add")); } } ~~~ 其实核心方法就两个 * inheritFromWidgetOfExactType:通过子widget可以通过BuildContext.inheritFromWidgetOfExactType(InheritedWidget)获得到InheritedWidget的实例,从而随时随地获取全局状态的值 * updateShouldNotify