Flutter 組件間通信

通信實現(xiàn)方式

回調(diào)通信

需求“點擊子組件拍皮,修改父組件的背景顏色與子組件背景顏色一致”
使用場景:一般用于子組件對父組件傳值。

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
///使用場景:一般用于子組件對父組件傳值看铆。
class ParentWidget extends StatefulWidget {
  final String? title;

  ParentWidget({Key? key,this.title}):super(key: key);

  @override
  State<StatefulWidget> createState() {
    return ParentWidgetState();
  }

}

class ParentWidgetState extends State<ParentWidget>{

  Color containerBg = Colors.orange;
  //回調(diào)函數(shù)
  void changeBackgroundColor(Color newColor){
    setState(() {
      containerBg = newColor;//修改狀態(tài)
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title??""),
      ),
      body: new Center(
        child: new GestureDetector(
          onTap: (){

          },
          child: new Container(
          width: 300,
          height: 300,
          color: containerBg,
          alignment: Alignment.center,
          child: new Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              childrenA(childrenABallback: changeBackgroundColor,),
              childrenB(childrenBBallback: changeBackgroundColor,),
            ],
          ),
        ),
        ),
      ),

    );
  }

}


///自組件 A
class childrenA extends StatelessWidget {

  final ValueChanged<Color>? childrenABallback;

  childrenA({Key? key,this.childrenABallback});

  @override
  Widget build(BuildContext context) {
    return new GestureDetector(
      onTap: (){
        childrenABallback!(Colors.green);
      },
      child: new Container(
        width: 80,
        height: 80,
        color: Colors.green,
        child: new Text("ChildrenA"),
      ),
    );
  }

}



///自組件 A
class childrenB extends StatelessWidget {

  final ValueChanged<Color>? childrenBBallback;

  childrenB({Key? key,this.childrenBBallback});

  @override
  Widget build(BuildContext context) {
    return new GestureDetector(
      onTap: (){
        childrenBBallback!(Colors.red);
      },
      child: new Container(
        width: 80,
        height: 80,
        color: Colors.red,
        child: new Text("ChildrenB"),
      ),
    );
  }

}

2941690359496_.pic.jpg

InheritedWidget 數(shù)據(jù)共享

場景:業(yè)務(wù)開發(fā)中經(jīng)常會碰到這樣的情況,多個Widget需要同步同一份全局數(shù)據(jù),比如點贊數(shù)授翻、評論數(shù)积暖、夜間模式等等藤为。
使用場景 一般用于父組件對子組件的跨組件傳值。

//模型數(shù)據(jù)
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
///一般用于父組件對子組件的跨組件傳值夺刑。
class InheritedTestModel {
  final int count;
  const InheritedTestModel(this.count);
}

//哨所(自定義InheritedWidget類)
class  InheritedContext extends InheritedWidget {

  //變量
  final InheritedTestModel inheritedTestModel;
  final Function() increment;
  final Function() reduce;

  InheritedContext({Key? key,
    required this.inheritedTestModel,
    required this.increment,
    required this.reduce,
    required Widget child,
  }) : super(key:key,child: child);

  //定義一個便捷方法缅疟,方便子樹中的widget獲取共享數(shù)據(jù)
  static InheritedContext? of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<InheritedContext>();
  }

  //是否重建取決于Widget組件是否相同
  @override
  bool updateShouldNotify(InheritedContext oldWidget) {
    return  inheritedTestModel != oldWidget.inheritedTestModel;
  }

}

class TestWidgetA extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print("TestWidgetA build");
    var of = InheritedContext.of(context);
    return new Padding(
        padding: const EdgeInsets.only(left: 10,top: 10,right: 10),
        child: new RaisedButton(
          textColor: Colors.black,
            child: Text("+"),
            onPressed: of?.increment
        ),
    );
  }
}

class TestWidgetB extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print("TestWidgetB build");
    var of = InheritedContext.of(context);
    return new Padding(
      padding: const EdgeInsets.only(left: 10,top: 10,right: 10),
      child: new RaisedButton(
          textColor: Colors.black,
          child: Text("-"),
          onPressed: of?.reduce
      ),
    );
  }
}

class TestWidgetC extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print("TestWidgetC build");
    var of = InheritedContext.of(context);
    var model = of?.inheritedTestModel;
    return new Padding(
      padding: const EdgeInsets.only(left: 10,top: 10,right: 10),
      child: new RaisedButton(
          textColor: Colors.black,
          child: Text('${model?.count}'),
          onPressed: (){

          }
      ),
    );
  }
}

class InheritedWidgetTestContainer extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new InheritedWidgetTestContainerState();
  }
}
class InheritedWidgetTestContainerState extends State<InheritedWidgetTestContainer> {

  InheritedTestModel? _inheritedTestModel;

  _initData(){
    _inheritedTestModel = new InheritedTestModel(0);
  }

  @override
  void initState() {
    _initData();
    super.initState();
  }

  _incrementCount(){
    setState(() {
      _inheritedTestModel = new InheritedTestModel(1 + (_inheritedTestModel?.count??0));
    });
  }

  _reduceCount(){
    setState(() {
      _inheritedTestModel = new InheritedTestModel((_inheritedTestModel?.count??0) - 1);
    });
  }

  @override
  Widget build(BuildContext context) {
    return InheritedContext(
        inheritedTestModel: _inheritedTestModel!,
        increment: _incrementCount,
        reduce: _reduceCount,
        child: Scaffold(
          appBar: AppBar(
            title: Text('inheritedWidgetTest'),
          ),
          body: new Center(
            child: Column(
              children: [
                TestWidgetA(),
                TestWidgetB(),
                TestWidgetC()
              ],
            ),
          ),
        ));
  }

}
2951690359496_.pic.jpg

Global Key通信

GlobalKey能夠跨Widget訪問狀態(tài)。
需求“點擊A子組件遍愿,修改B子組件的背景顏色為指定的‘藍色”
使用場景:一般用于跨組件訪問狀態(tài)

//父組件
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
///一般用于跨組件訪問狀態(tài)
class ParentGolablWidget extends  StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new ParentGolablWidgetState();
  }
}
GlobalKey<SubWidgetAState> subAkey = GlobalKey();
GlobalKey<SubWidgetBState> subBkey = GlobalKey();
class ParentGolablWidgetState extends State<ParentGolablWidget>{



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('組件化'),
      ),
      body: Center(
        child: Container(
          color: Colors.grey,
          width: 200,
          height: 200,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              SubWidgetA(key: subAkey),
              SubWidgetB(key: subBkey),
            ],
          ),
        ),
      ),
    );
  }

}


class SubWidgetA extends StatefulWidget{

  SubWidgetA({Key? key}):super(key: key);

  @override
  State<StatefulWidget> createState() {
    return SubWidgetAState();
  }


}

class SubWidgetAState extends State<SubWidgetA>{

  Color _backgroundColors = Colors.red;//紅色
  void updateBackGroundColors(Color colos){
    setState(() {
      _backgroundColors = colos;
    });
  }

  @override
  Widget build(BuildContext context) {
    return new GestureDetector(
      onTap: (){
        subBkey.currentState?.updateBackGroundColors(Colors.blue);
        setState(() {
          _backgroundColors = Colors.red;
        });
      },
      child: new Container(
        width: 80,
        height: 80,
        color: _backgroundColors,
        alignment: Alignment.center,
        child: Text('subWidgetA'),
      ),
    );
  }
}

//子組件B
class SubWidgetB extends StatefulWidget {
  SubWidgetB({Key? key}):super(key:key);
  @override
  State<StatefulWidget> createState() {
    return new SubWidgetBState();
  }
}

class SubWidgetBState extends State<SubWidgetB>{

  Color _backgroundColors = Colors.green;//紅色
  void updateBackGroundColors(Color colos){
    setState(() {
      _backgroundColors = colos;
    });
  }

  @override
  Widget build(BuildContext context) {
    return new GestureDetector(
      onTap: (){
        subAkey.currentState?.updateBackGroundColors(Colors.blue);
        setState(() {
          _backgroundColors = Colors.green;
        });
      },
      child: new Container(
        width: 80,
        height: 80,
        color: _backgroundColors,
        alignment: Alignment.center,
        child: Text('subWidgetB'),
      ),
    );
  }
}

2961690359497_.pic.jpg

ValueNotifier通信

ValueNotifier是一個包含單個值的變更通知器存淫,當它的值改變的時候,會通知它的監(jiān)聽

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class ValueNotifierData extends ValueNotifier<String>{
  ValueNotifierData(super.value);
}

class _WidgetOne extends StatefulWidget {
  ValueNotifierData? data;
  _WidgetOne({this.data});


  @override
  State<StatefulWidget> createState() {
    return _WidgetOneState();
  }
}

class _WidgetOneState extends State<_WidgetOne>{

  String? info = null;

  @override
  void initState() {
    super.initState();
    widget.data?.addListener(_handleValueChange);
    info = 'Initial message: ${widget.data?.value}';
  }

  @override
  void dispose() {
    widget.data?.removeListener(_handleValueChange);
    super.dispose();
  }

  void _handleValueChange(){
    setState(() {
      info = 'Message changed to: ${widget.data?.value}' ;
    });
  }

  @override
  Widget build(BuildContext context) {
    print("_WidgetOneState build()");
    return Container(
      child: Center(
        child: Text(info??''),
      ),
    );
  }

}

class ParentValueNotifierCommunication extends StatelessWidget {


  @override
  Widget build(BuildContext context) {
    ValueNotifierData vd = ValueNotifierData('Hello World');
    return Scaffold(
      appBar: AppBar(title: Text('Value Notifier Communication'),),
      body: _WidgetOne(data: vd,),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.refresh),
        onPressed: (){
          vd.value = 'Yes';
        },
      ),
    );
  }


2971690359498_.pic.jpg

第三方插件

event_bus來實現(xiàn)傳值

引入插件
import 'package:event_bus/event_bus.dart';
新建消息監(jiān)測類
import 'package:event_bus/event_bus.dart';
  EventBus eventBus = new EventBus();
  class TransEvent{
   String text;
   TransEvent(this.text);
  }
監(jiān)測類變化
eventBus.on<TransEvent>().listen((TransEvent data) => show(data.text));
void show(String val) {
 setState(() {
  data = val;
 });
}
觸發(fā)消息變化
eventBus.fire(new TransEvent('$inputText'));

項目地址
https://gitee.com/shiming_bai/textfluttertimer

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末沼填,一起剝皮案震驚了整個濱河市桅咆,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌坞笙,老刑警劉巖岩饼,帶你破解...
    沈念sama閱讀 221,273評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異薛夜,居然都是意外死亡籍茧,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,349評論 3 398
  • 文/潘曉璐 我一進店門梯澜,熙熙樓的掌柜王于貴愁眉苦臉地迎上來寞冯,“玉大人,你說我怎么就攤上這事腊徙〖蚴” “怎么了?”我有些...
    開封第一講書人閱讀 167,709評論 0 360
  • 文/不壞的土叔 我叫張陵撬腾,是天一觀的道長螟蝙。 經(jīng)常有香客問我,道長民傻,這世上最難降的妖魔是什么胰默? 我笑而不...
    開封第一講書人閱讀 59,520評論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮漓踢,結(jié)果婚禮上牵署,老公的妹妹穿的比我還像新娘。我一直安慰自己喧半,他們只是感情好奴迅,可當我...
    茶點故事閱讀 68,515評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著挺据,像睡著了一般取具。 火紅的嫁衣襯著肌膚如雪脖隶。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,158評論 1 308
  • 那天暇检,我揣著相機與錄音产阱,去河邊找鬼。 笑死块仆,一個胖子當著我的面吹牛构蹬,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播悔据,決...
    沈念sama閱讀 40,755評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼庄敛,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了蜜暑?” 一聲冷哼從身側(cè)響起铐姚,我...
    開封第一講書人閱讀 39,660評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎肛捍,沒想到半個月后隐绵,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,203評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡拙毫,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,287評論 3 340
  • 正文 我和宋清朗相戀三年依许,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片缀蹄。...
    茶點故事閱讀 40,427評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡峭跳,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出缺前,到底是詐尸還是另有隱情蛀醉,我是刑警寧澤,帶...
    沈念sama閱讀 36,122評論 5 349
  • 正文 年R本政府宣布衅码,位于F島的核電站拯刁,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏逝段。R本人自食惡果不足惜垛玻,卻給世界環(huán)境...
    茶點故事閱讀 41,801評論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望奶躯。 院中可真熱鬧帚桩,春花似錦、人聲如沸嘹黔。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,272評論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至郭蕉,卻和暖如春乏悄,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背恳不。 一陣腳步聲響...
    開封第一講書人閱讀 33,393評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留开呐,地道東北人烟勋。 一個月前我還...
    沈念sama閱讀 48,808評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像筐付,于是被迫代替她去往敵國和親卵惦。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,440評論 2 359

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