應(yīng)用場景不同
GetX
爭議較大
Provider
Provider 與 MVVM開發(fā)模式類似,React 框架轉(zhuǎn)過來的上手比較容易。Provider 是一個輕量級的狀態(tài)管理庫, 本質(zhì)上是一個基于 InheritedWidget 的封裝,通過對InheritedWidget的一次工程化的封裝把“暴露狀態(tài) → 訂閱變化 → 自動清理/銷毀”的流程做了統(tǒng)一抽象
依賴注入 : Provider 將狀態(tài)(例如一個數(shù)據(jù)對象或服務(wù))注入到 Widget 樹中。
事件通知 : 當(dāng)狀態(tài)發(fā)生變化時,Provider 會通知所有“監(jiān)聽”了這個狀態(tài)的 Widget。
第一步:添加依賴,引入 Provider 的庫,點(diǎn)擊 Pub Get
第二步:創(chuàng)建數(shù)據(jù)模型
class CounterModel extends ChangeNotifier {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners(); // 通知監(jiān)聽者數(shù)據(jù)已更新
}
}
第三步:提供數(shù)據(jù)模型
void main() {
runApp(
ChangeNotifierProvider(
create: (context) => CounterModel(),
child: const MyApp(),
),
);
}
第四步:消費(fèi)數(shù)據(jù)
使用 context.watch 和 context.read
class CounterBody extends StatelessWidget {
const CounterBody({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final count = context.watch<CounterModel>().count;
return Center(
child: Text(
'當(dāng)前計(jì)數(shù)值: $count',
style: Theme.of(context).textTheme.headlineMedium,
),
);
}
}
class CounterButton extends StatelessWidget {
const CounterButton({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return FloatingActionButton(
onPressed: () {
context.read<CounterModel>().increment();
},
child: const Icon(Icons.add),
);
}
}
第五步:基于 MultiProvider 優(yōu)化多個 Provider
Provider<Something>(
create: (_) => Something(),
child: Provider<SomethingElse>(
create: (_) => SomethingElse(),
child: Provider<AnotherThing>(
create: (_) => AnotherThing(),
child: someWidget,
),
),
),