共享状态管理(InheritedWidget)简单使用

本文介绍了Flutter中的InheritedWidget如何用于共享状态管理,它允许在widget树中自上而下传递数据。文章通过一个计数器示例展示了如何创建InheritedWidget,如何更新共享数据以及在子组件中如何使用这些数据。当共享数据发生变化时,依赖InheritedWidget的子组件会自动更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

共享状态管理-InheritedWidget的简单使用

InheritedWidget是 Flutter 中非常重要的一个功能型组件,它提供了一种在 widget 树中从上到下共享数据的方式,

InheritedWidget和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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值