[译]Flutter – 使用Provider实现状态管理
    		       		warning:
    		            这篇文章距离上次修改已过433天,其中的内容可能已经有所变动。
    		        
        		                
                
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
 
void main() {
  runApp(MyApp());
}
 
class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => Counter()),
      ],
      child: MaterialApp(
        title: 'Flutter Demo',
        home: MyHomePage(),
      ),
    );
  }
}
 
class Counter with ChangeNotifier {
  int _count = 0;
  int get count => _count;
 
  void increment() {
    _count++;
    notifyListeners();
  }
}
 
class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Flutter Provider Example"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Consumer<Counter>(
              builder: (context, counter, child) => Text(
                '${counter.count}',
                style: Theme.of(context).textTheme.headline4,
              ),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => Provider.of<Counter>(context, listen: false).increment(),
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}这段代码使用了Provider包来管理状态,它展示了如何创建一个简单的计数器应用程序。在这个例子中,我们使用ChangeNotifier类来包装我们的状态,并在需要时通过notifyListeners()来通知监听器状态已更新。我们使用Consumer小部件来响应状态的变化,并且在FloatingActionButton的onPressed回调中,我们通过Provider.of来获取Counter实例并调用increment方法。这是一个很基础的状态管理示例,但它展示了如何在实际应用程序中使用Provider来管理和响应状态的变化。
评论已关闭