Flutter 中的 ChangeNotifier 是一个通知机制,在其内部维护一个监听器列表,当某个属性发生变化时,通过调用 notifyListeners 来通知所有的监听器,以便监听器可以更新界面。ChangeNotifier 通常用于状态管理,可以在不需要依赖外部库的情况下实现简单的状态管理。
以下是一个简单的使用 ChangeNotifier 进行状态管理的代码示例:
import 'package:flutter/material.dart';
class Counter with ChangeNotifier {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners();
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final Counter counter = Counter();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'${counter.count}',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
counter.increment();
},
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
void main() {
runApp(MaterialApp(
title: 'Flutter Demo',
home: MyHomePage(title: 'Flutter Demo Home Page'),
));
}
在上面的代码示例中,Counter 类继承自 ChangeNotifier,使用 notifyListeners 来通知监听器 count 属性的变化。MyHomePage 中创建了一个 Counter 实例,通过 FloatingActionButton 的 onPressed 回调函数来调用 Counter.increment() 方法从而更新 count 属性的值。在 Text 中显示 count 属性的值,当其值发生变化时,Flutter 会自动调用 setState() 函数以更新显示。