flutter中InheritedWidget的介紹和運(yùn)用

InheritedWidget 不繼承自StatefulWidget僻弹,而是 InheritedWidget -> ProxyWidget -> Widget 這樣的繼承關(guān)系腐芍。簡單來說拓颓,InheritedWidget 的作用是向它的子 Widget 有效地傳播和分享數(shù)據(jù)竞穷,當(dāng) InheritedWidget 作為一個(gè)Parent Widget時(shí)儡嘶,它下面的Widget tree的所有Widget都可以去和 InheritedWidget 發(fā)生數(shù)據(jù)傳遞和交互侧啼。當(dāng)數(shù)據(jù)發(fā)生改變時(shí),一部分控件需要 rebuild泪蔫,另外的控件不需要 rebuild 的時(shí)候棒旗,可以使用 InheritedWidget,具體的介紹結(jié)合代碼來看撩荣。
下面是 InheritedWidget 的一個(gè)實(shí)例:

class MyInheritedWidget extends InheritedWidget {
   MyInheritedWidget({
      Key key,
      @required Widget child,
      this.data,
   }): super(key: key, child: child);
    
   final data;
    
   static MyInheritedWidget of(BuildContext context) {
      return context.inheritFromWidgetOfExactType(MyInheritedWidget);
   }

   @override
   bool updateShouldNotify(MyInheritedWidget oldWidget) => data != oldWidget.data;
}

updateShouldNotify 是必須重寫的一個(gè)方法铣揉,這個(gè)方法來決定什么時(shí)候需要去rebuild 控件
of 是一個(gè)類方法,返回了它自己餐曹,inheritFromWidgetOfExactType這個(gè)方法逛拱,我理解的是從父Widget中根據(jù)類型去找響應(yīng)的Widget,但這個(gè)方法還有其他的作用台猴,會在后面詳細(xì)介紹朽合。
初始化方法中俱两,會傳一個(gè)Child,并傳遞給super曹步,也就是它的子Widget宪彩。

使用這個(gè)類:

class MyParentWidget... {
   ...
   @override
   Widget build(BuildContext context){
      return new MyInheritedWidget(
         data: counter,
         child: new Row(
            children: <Widget>[
               ...
            ],
         ),
      );
   }
}

子Widget怎么獲取數(shù)據(jù)?

class MyChildWidget... {
   ...
    
   @override
   Widget build(BuildContext context){
      final MyInheritedWidget inheritedWidget = MyInheritedWidget.of(context);
        
      ///
      /// From this moment, the widget can use the data, exposed by the MyInheritedWidget
      /// by calling:  inheritedWidget.data
      ///
      return new Container(
         color: inheritedWidget.data.color,
      );
   }
}

應(yīng)用場景:

  • Widget A是一個(gè)按鈕讲婚,點(diǎn)擊的時(shí)候購物車數(shù)量加1.
  • Widget B是一個(gè)顯示購物車數(shù)量的文本.
  • Widget C是顯示一個(gè)固定的文本
  • 在點(diǎn)擊Widget A的時(shí)候尿孔,Widget B刷新數(shù)據(jù),而不需要rebuild Widget C

代碼如下:

class Item {
   String reference;

   Item(this.reference);
}

class _MyInherited extends InheritedWidget {
  _MyInherited({
    Key key,
    @required Widget child,
    @required this.data,
  }) : super(key: key, child: child);

  final MyInheritedWidgetState data;

  @override
  bool updateShouldNotify(_MyInherited oldWidget) {
    return true;
  }
}

class MyInheritedWidget extends StatefulWidget {
  MyInheritedWidget({
    Key key,
    this.child,
  }): super(key: key);

  final Widget child;

  @override
  MyInheritedWidgetState createState() => new MyInheritedWidgetState();

  static MyInheritedWidgetState of(BuildContext context){
    return (context.inheritFromWidgetOfExactType(_MyInherited) as _MyInherited).data;
  }
}

class MyInheritedWidgetState extends State<MyInheritedWidget>{
  /// List of Items
  List<Item> _items = <Item>[];

  /// Getter (number of items)
  int get itemsCount => _items.length;

  /// Helper method to add an Item
  void addItem(String reference){
    setState((){
      _items.add(new Item(reference));
    });
  }

  @override
  Widget build(BuildContext context){
    return new _MyInherited(
      data: this,
      child: widget.child,
    );
  }
}

class MyTree extends StatefulWidget {
  @override
  _MyTreeState createState() => new _MyTreeState();
}

class _MyTreeState extends State<MyTree> {
  @override
  Widget build(BuildContext context) {
    return new MyInheritedWidget(
      child: new Scaffold(
        appBar: new AppBar(
          title: new Text('Title'),
        ),
        body: new Column(
          children: <Widget>[
            new WidgetA(),
            new Container(
              child: new Row(
                children: <Widget>[
                  new Icon(Icons.shopping_cart),
                  new WidgetB(),
                  new WidgetC(),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class WidgetA extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final MyInheritedWidgetState state = MyInheritedWidget.of(context);
    return new Container(
      child: new RaisedButton(
        child: new Text('Add Item'),
        onPressed: () {
          state.addItem('new item');
        },
      ),
    );
  }
}

class WidgetB extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final MyInheritedWidgetState state = MyInheritedWidget.of(context);
    return new Text('${state.itemsCount}');
  }
}

class WidgetC extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Text('I am Widget C');
  }
}

解釋說明:

  • 當(dāng)點(diǎn)擊Widget A的時(shí)候筹麸,_MyInherited 會被重新創(chuàng)建一個(gè)
  • MyInheritedWidget 相當(dāng)于是一個(gè)購物車活合,它的State通過static MyInheritedWidgetState of(BuildContext context)可以獲取到.
  • MyInheritedWidgetState 提供了公開的方法,getter (itemsCount)和addItem竹捉,這兩個(gè)方法可以被子Widget調(diào)用.
  • 每次我們添加一項(xiàng)到購物車時(shí)芜辕,MyInheritedWidgetState會rebuild

InheritedWidget是怎么去通知子Widget刷新數(shù)據(jù)的呢尚骄?

當(dāng)一個(gè)子Widget調(diào)用MyInheritedWidget.of(context)時(shí)块差,會走下面的代碼,把它自己的context傳進(jìn)來

static MyInheritedWidgetState of(BuildContext context) {
    return (context.inheritFromWidgetOfExactType(_MyInherited) as _MyInherited).data;
  }

這個(gè)方法其實(shí)是做了兩件事:

  • 獲取MyInheritedWidgetState里面的數(shù)據(jù)
  • 會將調(diào)用該方法的Widget加入訂閱者行列倔丈,當(dāng)數(shù)據(jù)發(fā)生改變的時(shí)候憨闰,會通知這些Widget刷新數(shù)據(jù),也就是rebuild.

工作的原理總結(jié)起來如下:
因?yàn)閃idget A和Widget B訂閱了InheritedWidget,所以點(diǎn)擊Widget A的時(shí)候會發(fā)生:

  • 觸發(fā)了MyInheritedWidgetState的addItem的方法
  • MyInheritedWidgetState的addItem的方法添加了新的一項(xiàng)數(shù)據(jù)到data中
  • 觸發(fā)了setState()需五,MyInheritedWidgetState rebuild
  • 重新創(chuàng)建了一個(gè) _MyInherited 對象鹉动,傳入了新的數(shù)據(jù),記錄了新的State
  • _MyInherited去查看是否需要通知訂閱者宏邮,因?yàn)榉祷氐氖莟rue泽示,所以會通知訂閱者
  • Widget A和Widget B 被 rebuild了,Widget C沒有被訂閱蜜氨,所以不會被rebuild

因?yàn)槭聦?shí)上Widget A是不需要被通知的械筛,所以為了解決這個(gè)問題,需要修改代碼

static MyInheritedWidgetState of([BuildContext context, bool rebuild = true]){
    return (rebuild ? context.inheritFromWidgetOfExactType(_MyInherited) as _MyInherited
                    : context.ancestorWidgetOfExactType(_MyInherited) as _MyInherited).data;
  }

ancestorWidgetOfExactType 方法只會去獲取Widget飒炎,不會發(fā)生訂閱埋哟,所以Widget A就不會訂閱了。

參考鏈接: https://www.didierboelens.com/2018/06/widget---state---context---inheritedwidget/

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末郎汪,一起剝皮案震驚了整個(gè)濱河市赤赊,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌煞赢,老刑警劉巖抛计,帶你破解...
    沈念sama閱讀 222,000評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異照筑,居然都是意外死亡吹截,警方通過查閱死者的電腦和手機(jī)录豺,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,745評論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來饭弓,“玉大人双饥,你說我怎么就攤上這事〉芏希” “怎么了咏花?”我有些...
    開封第一講書人閱讀 168,561評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長阀趴。 經(jīng)常有香客問我昏翰,道長,這世上最難降的妖魔是什么刘急? 我笑而不...
    開封第一講書人閱讀 59,782評論 1 298
  • 正文 為了忘掉前任棚菊,我火速辦了婚禮,結(jié)果婚禮上叔汁,老公的妹妹穿的比我還像新娘统求。我一直安慰自己,他們只是感情好据块,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,798評論 6 397
  • 文/花漫 我一把揭開白布码邻。 她就那樣靜靜地躺著,像睡著了一般另假。 火紅的嫁衣襯著肌膚如雪像屋。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,394評論 1 310
  • 那天边篮,我揣著相機(jī)與錄音己莺,去河邊找鬼。 笑死戈轿,一個(gè)胖子當(dāng)著我的面吹牛凌受,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播凶杖,決...
    沈念sama閱讀 40,952評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼胁艰,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了智蝠?” 一聲冷哼從身側(cè)響起腾么,我...
    開封第一講書人閱讀 39,852評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎杈湾,沒想到半個(gè)月后解虱,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,409評論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡漆撞,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,483評論 3 341
  • 正文 我和宋清朗相戀三年殴泰,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了于宙。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,615評論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡悍汛,死狀恐怖捞魁,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情离咐,我是刑警寧澤谱俭,帶...
    沈念sama閱讀 36,303評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站宵蛀,受9級特大地震影響昆著,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜术陶,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,979評論 3 334
  • 文/蒙蒙 一凑懂、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧梧宫,春花似錦接谨、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,470評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽兆解。三九已至馆铁,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間锅睛,已是汗流浹背埠巨。 一陣腳步聲響...
    開封第一講書人閱讀 33,571評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留现拒,地道東北人辣垒。 一個(gè)月前我還...
    沈念sama閱讀 49,041評論 3 377
  • 正文 我出身青樓,卻偏偏與公主長得像印蔬,于是被迫代替她去往敵國和親勋桶。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,630評論 2 359

推薦閱讀更多精彩內(nèi)容