美文网首页
Flutter状态管理之Provider

Flutter状态管理之Provider

作者: xulj100 | 来源:发表于2020-04-21 19:45 被阅读0次

    Provider是目前官方推荐的全局状态管理工具,可以实现跨组件数据的传递。

    1、添加provider依赖

    进入https://pub.dev/packages搜索provider,找到对应版本,在pubspec.yaml文件添加:

    provider: ^4.0.5
    
    • ChangeNotifier:真正数据(状态)存放的地方
    • ChangeNotifierProvider:Widget树中提供数据(状态)的地方,会在其中创建对应的ChangeNotifier
    • Consumer:Widget树中需要使用数据(状态)的地方

    2、创建自己需要共享的数据继承ChangeNotifier

    • 我们可以使用继承自ChangeNotifier,也可以使用混入with
    • 新建一个方法,调用notifyListeners(),通知所有的Consumer进行更新
    import 'package:flutter/material.dart';
    
    class UserInfo {
      String name = "leo";
      int age = 10;
      UserInfo(this.name, this.age);
    }
    
    /// with ChangeNotifier
    class MyCounter with ChangeNotifier {
      UserInfo _userInfo = UserInfo("leo", 10);
      UserInfo get userInfo => _userInfo;
    
      void add() {
        _userInfo.age++;
        notifyListeners();
      }
    }
    
    ///  extends ChangeNotifier
    class MySubtract extends ChangeNotifier {
      UserInfo _userInfo = UserInfo("jim", 100);
      UserInfo get userInfo => _userInfo;
    
      void sub() {
        _userInfo.age--;
        notifyListeners();
      }
    }
    
    

    3、在Widget Tree中插入ChangeNotifierProvider

    void main() => runApp(
      MultiProvider(
        providers: [
          ChangeNotifierProvider(create: (ctx)=>MyCounter()),
          ChangeNotifierProvider(create: (ctx)=>MySubtract()),
        ],
        child: MyApp(),
      )
    );
    

    4、使用共享数据

    import 'package:dart/demo/user_view_model.dart';
    import 'package:flutter/material.dart';
    import 'package:provider/provider.dart';
    
    void main() => runApp(
      MultiProvider(
        providers: [
          ChangeNotifierProvider(create: (ctx)=>MyCounter()),
          ChangeNotifierProvider(create: (ctx)=>MySubtract()),
        ],
        child: MyApp(),
      )
    );
    
    class MyApp extends StatelessWidget {
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter widget',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: MyHomePage(),
        );
      }
    }
    
    class MyHomePage extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text("Flutter Provider"),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                MyContainer1(),
                SizedBox(height: 30),
                MyContainer2()
              ],
            ),
            ),
          );
      }
    }
    
    class MyContainer1 extends StatefulWidget{
    
      @override
      _MyContainer1State createState() => _MyContainer1State();
    }
    
    class _MyContainer1State extends State<MyContainer1> {
      @override
      Widget build(BuildContext context) {
        final String name1=Provider.of<MyCounter>(context).userInfo.name;
        final int age1=Provider.of<MyCounter>(context).userInfo.age;
    
        final String name2=Provider.of<MySubtract>(context).userInfo.name;
        final int age2=Provider.of<MySubtract>(context).userInfo.age;
    
        return Column(
          children: <Widget>[
            Text("Container1 name1=$name1  age1=$age1",style: myTextStyle1()),
            Text("Container1 name2=$name2  age2=$age2",style: myTextStyle2()),
          ],
        );
      }
    }
    
    TextStyle myTextStyle1(){
      return TextStyle(fontSize: 20,color: Colors.blue);
    }
    
    TextStyle myTextStyle2(){
      return TextStyle(fontSize: 20,color: Colors.green);
    }
    
    class MyContainer2 extends StatefulWidget{
    
      @override
      _MyContainer2State createState() => _MyContainer2State();
    }
    
    class _MyContainer2State extends State<MyContainer2> {
      @override
      Widget build(BuildContext context) {
        return Container(
          child: Consumer2<MyCounter,MySubtract>(
           builder: (ctx,counterVM,subtractVM,child){
             return Column(
               children: <Widget>[
                 Text("Container2 name1=${counterVM.userInfo.name}  age1=${counterVM.userInfo.age}",style:myTextStyle1()),
                 Text("Container2 name2=${subtractVM.userInfo.name}  age2=${subtractVM.userInfo.age}",style:myTextStyle2()),
                 SizedBox(height: 30,),
                 RaisedButton(
                   child:Text("点 击"),
                   onPressed: (){
                     counterVM.add();
                     subtractVM.sub();
                   },
                 ),
               ],
             );
           },
          ),
        );
      }
    }
    

    点击改变数据,看效果图:


    image01.gif

    相关文章

      网友评论

          本文标题:Flutter状态管理之Provider

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