【问题标题】:Riverpod - fetch data in ConsumerWidget when accessing itRiverpod - 访问时在 ConsumerWidget 中获取数据
【发布时间】: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


    【解决方案1】:

    要在观看 stateNotifierProvider 后调用 fetchData(),您需要在 StateNotifier 的构造函数中调用它,如下所示:

    MyStateNotifier(this.databaseService) : super(CustomStateInit()){fetchData();}
    

    【讨论】:

      猜你喜欢
      • 2021-04-29
      • 2021-01-19
      • 2021-03-27
      • 2021-02-26
      • 1970-01-01
      • 2022-11-21
      • 2021-01-18
      • 1970-01-01
      • 2021-08-10
      相关资源
      最近更新 更多