美文网首页
flutter provider管理状态

flutter provider管理状态

作者: Albert新荣 | 来源:发表于2020-12-15 18:10 被阅读0次

    自己稍微看了一下别人的然后稍微修改了一下
    建一个自定义的provider ,我用了demo里面的名字

    import 'package:flutter/material.dart';
    import 'package:flutter/foundation.dart';
    
    class Counter with ChangeNotifier, DiagnosticableTreeMixin { //后面这个是对应的是foundation库
      int _value = 0; //我用这个值来管理tabbar的index,我这边需求是,提交信息之后要返回tabbar 然后切到某个页面
      int get value => _value; //Get方法
      selectIndex(int index) { //设置index
        _value = index;
        notifyListeners();
      }
    
      selectTaskPage() { //默认选择tabbar第一个值
        _value = 0;
        notifyListeners();
      }
    }
    
      @override
      Widget build(BuildContext context) {
        _initScreenUnitl(context);
        List<Widget> vcs = [Task(), Taskpush(), Me()];
        return Scaffold(
          bottomNavigationBar: BottomNavigationBar(
            // 底部导航
            items: <BottomNavigationBarItem>[
              BottomNavigationBarItem(icon: Icon(Icons.home), title: Text('拼车')),
              BottomNavigationBarItem(
                  icon: Icon(Icons.edit_location_outlined), title: Text('发布')),
              BottomNavigationBarItem(
                  icon: Icon(Icons.perm_identity), title: Text('我的')),
            ],
            currentIndex: context.watch<Counter>().value, //观察并读取这个值,
            fixedColor: Colors.blue,
            onTap: _onItemTapped,
          ),
          body: vcs[context.watch<Counter>().value], // 底部导航 ////观察并读取这个值,同上
        );
      }
    
      void _onItemTapped(int index) {
        context.read<Counter>().selectIndex(index); //设置这个值,tabbar 也是通过修改这个值来实现切换tabbar
      }
    }
    
    context.read<Counter>().selectTaskPage(); //在任意页面,调用这个方法,直接修改主页的切换的参数直接实现切换页面的操作 ,仔细看上面我这个方法里面写个常量,直接切到0的页面,就是tabbar的第一个页面
    

    上面是实例,下面简要的一个使用方法
    简略的说一下

    先定义一个类,如下
    import 'package:flutter/material.dart';
    import 'package:flutter/foundation.dart';
    
    class Counter with ChangeNotifier, DiagnosticableTreeMixin { //后面这个是对应的是foundation库
      int _value = 0; //我用这个值来管理tabbar的index,我这边需求是,提交信息之后要返回tabbar 然后切到某个页面
      int get value => _value; //Get方法
      selectIndex(int index) { //设置index
        _value = index;
        notifyListeners(); //这个要记得,不然无法监听这个值的改变
      }
    
    
    取值的方法为
    context.watch<Counter>().value
    
    设值的方法为
     context.read<Counter>().selectIndex(index);
    

    相关文章

      网友评论

          本文标题:flutter provider管理状态

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