共享状态管理-InheritedWidget的简单使用
InheritedWidget
是 Flutter 中非常重要的一个功能型组件,它提供了一种在 widget 树中从上到下共享数据的方式,
InheritedWidge
t和React
中的context
功能类似,可以实现跨组件数据的传递。InheritedWidget
的在 widget 树中数据传递方向是从上到下的。
先查看InheritedWidget
源码,
- InheritedWidget 的构造中需要传入 child,这个child就是需要使用共享数据的子widget
- updateShouldNotify 这个抽象方法需要子类实现
abstract class InheritedWidget extends ProxyWidget {
/// Abstract const constructor. This constructor enables subclasses to provide
/// const constructors so that they can be used in const expressions.
const InheritedWidget({
super.key, required super.child });
InheritedElement createElement() => InheritedElement(this);
/// Whether the framework should notify widgets that inherit from this widget.
///
/// When this widget is rebuilt, sometimes we need to rebuild the widgets that
/// inherit from this widget but sometimes we do not. For example, if the data
/// held by this widget is the same as the data held by `oldWidget`, then we
/// do not need to rebuild the widgets that inherited the data held by
/// `oldWidget`.
///
/// The framework distinguishes these cases by calling this function with the
/// widget that previously occupied this location in the tree as an argument.
/// The given widget is guaranteed to have the same [runtimeType] as this
/// object.
bool updateShouldNotify(covariant InheritedWidget oldWidget);
}
来定义 “计数器”示例应用程序一个共享数据的InheritedWidget
,需要继承自 InheritedWidget
, 如下:
class CounterWidget extend