【发布时间】:2022-01-01 23:27:35
【问题描述】:
我有一个 StateNotifier,我想在小部件中使用它的状态。
据我所知,如果您在构建中使用 ref.watch 观看 StateNotifierProvider,则每次状态更改时都会重新构建小部件。
现在,在 StateNotifier 中,我有一个 DatabaseService 实例来调用 api 请求并相应地设置状态,在 ConsumerWidget 中我观察状态。
问题是,我想在第一次构建小部件时调用 StateNotifier 中定义的 fetch 方法,以便显示从数据库中检索到的数据。
类似的东西
class MyStateNotifier extends StateNotifier<CustomState> {
final DatabaseService databaseService;
MyStateNotifier(this.databaseService) : super(CustomStateInit());
Future<void> fetchData() async {
state = CustomStateLoading();
final result = await databaseService.apiRequest();
state = CustomStateSuccess(result);
}
}
final stateNotifierProvider = StateNotifierProvider((ref) => MyStateNotifier());
在小部件中
class MyWidget extends ConsumerWidget {
// I have to call the MyStateNotifier fetchData() method to get the data
Widget build(BuildContext context, WidgetRef ref) {
final data = ref.watch(stateNotifierProvider);
return Column(
children: data.map((e) => Text(e)).toList()
);
}
}
【问题讨论】:
标签: flutter riverpod flutter-state