v0.10.0
flutter_state_management
一组帮助类,使使用 ChangeNotifier 进行状态管理更加简便
4喜欢 111近 30 天下载160Pub 分数
AndroidiOSWebmacOSWindowsLinux
MohiuddinM/flutter_state_management open-source repository details.
{"sdk":"flutter"}{"sdk":"flutter"}^5.0.0^5.0.0以下为英文项目原文快照,最新内容请访问 GitHub。
Just a couple of utility classes to make it easier to use Flutter framework's built-in ChangeNotifier and Listenable for state management.
Create your model class
class Counter extends StateNotifier<int, String> {
Counter() : super(const Active(data: 0));
void increment() async {
setWaiting();
await Future.delayed(const Duration(seconds: 2));
if (data > 20) {
setFailed('greater than 20');
} else {
setActive(data + 1);
}
}
}
Or if you want the state to persist across restarts
class Counter extends PersistedStateNotifier<int, String> {
Counter() : super(IsarKeyValue(), startState: 0);
void increment() async {
setWaiting();
await Future.delayed(const Duration(seconds: 2));
if (data > 20) {
setFailed('greater than 20');
} else {
setActive(data + 1);
}
}
}
final counter = Counter();
ValueListenableBuilder(
valueListenable: counter,
child: Text()
builder: (context, state, child) => // return updated UI here (can also use counter.builderArg here)
child: const Text('Hello'),
),
);
You can also use builderArg helper:
builder: counter.builderArg(
onActive: ,
onWaiting: ,
onNone: ,
onFailure: ,
),
final counter = Counter();
counter.builder(
onActive: (context, data) => Text(data.toString()),
),
\
Convert your existing StatelessWidget to RStatelessWidget, and StatefulWidget to RStatefulWidget and and just watch the model inside the build method:
class CounterText extends RStatelessWidget {
@override
Widget build(BuildContext context) {
counter.watch(context); // call watch inside the build method (do not use any if)
return Text(data.toString());
}
}