最小可复制代码:
class FooPage extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final asyncValue = ref.watch(sp);
print('loading = ${asyncValue.isLoading}, value = ${asyncValue.valueOrNull}');
return Container();
}
}
final sp = StreamProvider<int>((ref) async* {
yield 0;
});
输出:
flutter: loading = true, value = null
flutter: loading = false, value = 0
flutter: loading = false, value = 0
它叫什么,或者为什么行flutter: loading = false, value = 0
重复了两次?
在您的代码中,StreamProvider不会被多次调用,您的构建方法会。
,如果您将您的提供商更改为
final sp = StreamProvider<int>((ref) async* {
print('provider called');
yield 0;
});
这个函数不会被多次调用。
Build方法可以被多次调用,并且ref.watch
会给你相同的provider实例,除非它自上次构建以来被更改或无效。