Flutter 组件间通信

通信实现方式

回调通信

需求“点击子组件,修改父组件的背景颜色与子组件背景颜色一致”
使用场景:一般用于子组件对父组件传值。

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;
  //回调函数
  void changeBackgroundColor(Color newColor){
    setState(() {
      containerBg = newColor;//修改状态
    });
  }

  @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 数据共享

场景:业务开发中经常会碰到这样的情况,多个Widget需要同步同一份全局数据,比如点赞数、评论数、夜间模式等等。
使用场景 一般用于父组件对子组件的跨组件传值。

//模型数据
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获取共享数据
  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访问状态。
需求“点击A子组件,修改B子组件的背景颜色为指定的‘蓝色”
使用场景:一般用于跨组件访问状态

//父组件
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
///一般用于跨组件访问状态
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是一个包含单个值的变更通知器,当它的值改变的时候,会通知它的监听

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来实现传值

引入插件
import 'package:event_bus/event_bus.dart';
新建消息监测类
import 'package:event_bus/event_bus.dart';
  EventBus eventBus = new EventBus();
  class TransEvent{
   String text;
   TransEvent(this.text);
  }
监测类变化
eventBus.on<TransEvent>().listen((TransEvent data) => show(data.text));
void show(String val) {
 setState(() {
  data = val;
 });
}
触发消息变化
eventBus.fire(new TransEvent('$inputText'));

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,911评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,014评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 142,129评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,283评论 1 264
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,159评论 4 357
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,161评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,565评论 3 382
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,251评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,531评论 1 292
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,619评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,383评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,255评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,624评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,916评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,199评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,553评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,756评论 2 335

推荐阅读更多精彩内容