面试题答案
一键面试- 创建 Provider:
- 首先,定义一个用于管理计数器状态的类,例如:
class CounterModel with ChangeNotifier { int _count = 0; int get count => _count; void increment() { _count++; notifyListeners(); } }
- 然后,在应用的顶层使用
Provider
来提供这个状态。通常在MaterialApp
或CupertinoApp
外面包裹Provider
:
void main() { runApp( Provider<CounterModel>( create: (context) => CounterModel(), child: MyApp(), ), ); }
- 在 Widget 中获取状态:
- 可以使用
Consumer
widget 来获取状态并构建依赖于该状态的 UI。例如:
class MyHomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Counter Example'), ), body: Center( child: Consumer<CounterModel>( builder: (context, counter, child) { return Text( 'Count: ${counter.count}', style: TextStyle(fontSize: 24), ); }, ), ), ); } }
- 也可以使用
context.watch
或context.read
方法获取状态。context.watch
会在状态变化时重建当前 widget,而context.read
不会。例如:
class MyHomePage extends StatelessWidget { @override Widget build(BuildContext context) { final counter = context.watch<CounterModel>(); return Scaffold( appBar: AppBar( title: Text('Counter Example'), ), body: Center( child: Text( 'Count: ${counter.count}', style: TextStyle(fontSize: 24), ), ), ); } }
- 可以使用
- 更新状态:
- 在需要更新状态的地方,获取
CounterModel
实例并调用其更新方法。例如,在按钮的点击事件中:
class MyHomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Counter Example'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Consumer<CounterModel>( builder: (context, counter, child) { return Text( 'Count: ${counter.count}', style: TextStyle(fontSize: 24), ); }, ), ElevatedButton( onPressed: () { context.read<CounterModel>().increment(); }, child: Text('Increment'), ) ], ), ), ); } }
- 在需要更新状态的地方,获取