美文网首页
Flutter - 数据共享

Flutter - 数据共享

作者: 恍然如梦_b700 | 来源:发表于2020-06-19 00:02 被阅读0次

    在开发中我们经常会用到InheritedWidget,可以在它的任意子widget获取到数据
    < 英 [ɪn'herɪtɪd]

    import 'package:flutter/material.dart';
    
    //数据共享!
    class MyData extends InheritedWidget {
      MyData({this.data, Widget child}) : super(child: child);
      final int data; //需要在子Widget中共享的数据!
    
      //提供一个方法让子Widget访问的共享数据!
      static MyData of(BuildContext context) {
        return context.dependOnInheritedWidgetOfExactType<MyData>();
      }
    
      @override
      bool updateShouldNotify(MyData oldWidget) {
        return oldWidget.data != data;
      }
    }
    
    
    
    class InheritedDemo extends StatefulWidget {
      @override
      _InheritedDemoState createState() => _InheritedDemoState();
    }
    
    class _InheritedDemoState extends State<InheritedDemo> {
      int count = 1;
    
      @override
      Widget build(BuildContext context) {
        return MyData(
          data: count,
          child: Column(
            children: <Widget>[
              Test1(),
              RaisedButton(
                child: Text('我是按钮'),
                //setState!
    
                onPressed: () => setState(() {
                  count++;
                }),
              )
            ],
          ),
        );
      }
    }
    
    class Test1 extends StatelessWidget {
    //  final count;
    //  Test1(this.count);
      @override
      Widget build(BuildContext context) {
        return Test2();
      }
    }
    
    class Test2 extends StatelessWidget {
    //  final count;
    //  Test2(this.count);
      @override
      Widget build(BuildContext context) {
        return Test3();
      }
    }
    
    class Test3 extends StatefulWidget {
    //  final count;
    //  Test3(this.count);
      @override
      _Test3State createState() => _Test3State();
    }
    
    class _Test3State extends State<Test3> {
      @override
      Widget build(BuildContext context) {
        return Text(MyData.of(context).data.toString());
      }
    
      @override
      void didChangeDependencies() {
        print('didChangeDependencies');
        super.didChangeDependencies();
      }
    }
    
    

    相关文章

      网友评论

          本文标题:Flutter - 数据共享

          本文链接:https://www.haomeiwen.com/subject/jelmxktx.html