Flutter RiverPod – 如何使两个不同的小部件从同一个FutureProvider中获取数据?

huangapple go评论53阅读模式
英文:

Flutter RiverPod - how to have two different widgets draw data from same FutureProvider?

问题

我有一个复杂的多面板显示,其中每个面板都是一个独特的小部件,每个小部件的数据都来自于一个RiverPod Future提供程序。

其中两个小部件将使用相同的RiverPod Future提供程序的数据,像这样...

@override
Widget build(BuildContext context) {
  int? aHabitId = _getHabitId();
  final anEditFuture = ref.watch(findHabitOnlyProvider(aHabitId));
  return anEditFuture.when(
    data: (data) => _buildView(data!),
    error: (e, st) => Center(
      child: Text(e.toString()),
    ),
    loading: () => const Center(
        child: SizedBox(
            width: 50.0, height: 50.0, child: CircularProgressIndicator())),
  );
}

如果我在每个独立的小部件中包含这段代码块,那么Future提供程序会分别为每个小部件调用吗?如何结构化以使Future提供程序仅被调用一次,并且数据对两个小部件都可用?

如果我在每个独立的小部件中包含这段代码块,那么Future提供程序会分别为每个小部件调用吗?如何结构化以使Future提供程序仅被调用一次,并且数据对两个小部件都可用?

英文:

I have a complex multi panel display where each panel is a distinct widget and the data for each widget is sourced from a RiverPod Future provider.

Two of these widgets will use data from the same RiverPod Future provider, like...

  @override
  Widget build(BuildContext context) {
    int? aHabitId = _getHabitId();
    final anEditFuture = ref.watch(findHabitOnlyProvider(aHabitId));
    return anEditFuture.when(
      data: (data) => _buildView(data!),
      error: (e, st) => Center(
        child: Text(e.toString()),
      ),
      loading: () => const Center(
          child: SizedBox(
              width: 50.0, height: 50.0, child: CircularProgressIndicator())),
    );
  }

If I include this code block in each distinct widget, will the Future Provider be called separately for each widget? How can I structure this so that the the Future provider is only called once, and the data is made availble to both widgets?

答案1

得分: 1

FutureProvider 只会被调用一次,结果会被缓存。因此,重复监听此提供程序将返回缓存的值。

当然,如果您的 aHabitId 参数相同。

英文:

The FutureProvider will only be called once and the result will be cached. Therefore, repeatedly listening to this provider will return a cached value.

Of course, if your aHabitId argument is the same.

huangapple
  • 本文由 发表于 2023年6月5日 19:10:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76405839.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定