美文网首页
Flutter Provider使用

Flutter Provider使用

作者: Lucky_1122 | 来源:发表于2024-07-10 15:02 被阅读0次

    1.创建状态

    class Counter with ChangeNotifier{
      int count = 0;
      void add(){
        count += 1;
        notifierListenters();
      }
    }
    

    2.提供状态

    runAPP(){
      ChangeNotifierProvider(
        create:(context) => Counter()
        child:MyApp()
      )
    }
    

    3.监听状态

    Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            backgroundColor: Theme.of(context).colorScheme.inversePrimary,
            title: Text(widget.title),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
              //绑定监听
                Consumer<Counter>(
                  builder: (context, value, child) {
                    return Text('${value.count}');
                  },
                ),
                const Text(
                  'You have pushed the button this many times:',
                ),
          //这样监听也行
                Text(
                  '${Provider.of<Counter>(context, listen: true).count}',
                  style: Theme.of(context).textTheme.headlineMedium,
                ),
              ],
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: _incrementCounter,
            tooltip: 'Increment',
            child: const Icon(Icons.add),
          ), // This trailing comma makes auto-formatting nicer for build methods.
        );
      }
    

    4.触发

     void _incrementCounter() {
        Provider.of<Counter>(context, listen: false).increment();
      }
    

    相关文章

      网友评论

          本文标题:Flutter Provider使用

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