Flutter Provider使用

2024-07-10  本文已影响0人  Lucky_1122

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();
  }
上一篇 下一篇

猜你喜欢

热点阅读