英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论