【问题标题】:How can I recall a futureprovider (riverpod) on build如何在构建时调用 futureprovider (riverpod)
【发布时间】:2021-03-23 19:53:18
【问题描述】:

我有一个显示产品的简单页面,我正在尝试使用riverpod 和futureprovider,但仅在我第一次访问该页面时才调用future?

final productInfo = FutureProvider<Map<String, dynamic>>((ref) async {
  final response =
      await http.get('https://www.api.com/$clickedID');
  final content = json.decode(response.body) as Map<String, dynamic>;
  return content;
});

【问题讨论】:

    标签: flutter dart riverpod


    【解决方案1】:

    请使用

    final userProvider = StreamProvider<User>(
     final response =
          await http.get('https://www.api.com/$clickedID');
      final content = json.decode(response.body) as Map<String, dynamic>;
      return content;
    );
    

    现在您可以使用watch 收听提供者,

      AsyncValue<User> user = watch(userProvider);
    

    【讨论】:

    • 然后我得到一个类型错误,Future 不能分配给 Stream
    • 使用流构建器而不是未来的构建器。
    • 好的,谢谢,即使它不是流也可以吗?
    【解决方案2】:

    没有内置功能,但您可以在以后使用相同的未来覆盖该值。

    recallProductInfoFutureProvider() {
    final response = http.get('https://www.api.com/$clickedID');
      final content = json.decode(response.body) as Map<String, dynamic>;
    productInfo.overrideWithValue(content)
    }
    

    考虑使用 StreamProvider 并在 Consumer 内部观察,以在 overrideWithValue 上更新 UI。

    【讨论】:

      【解决方案3】:

      使用最近的 Riverpod,您可以通过 ref.refresh(userProvider) 刷新提供程序。

      【讨论】:

        猜你喜欢
        • 2020-11-11
        • 2021-12-24
        • 1970-01-01
        • 2022-10-19
        • 2022-08-14
        • 2022-07-28
        • 2022-12-14
        • 2021-05-30
        • 1970-01-01
        相关资源
        最近更新 更多