[英]The Argument type 'Context' can't be assigned to the parameter type 'BuildContext' - Flutter
[英]Flutter Riverpod - .autoDispose - The argument type 'AutoDisposeProvider' can't be assigned to the parameter type 'AlwaysAliveProviderBase'
根据文档,当我收到此错误时,我应该用.autoDispose
标记两个Providers
:
参数类型“AutoDisposeProvider”不能分配给参数类型“AlwaysAliveProviderBase”
为什么在这个简约示例中我仍然收到错误?
final a = FutureProvider.autoDispose<List<String>>((ref) {
return Future.value(["test"]);
});
final b = FutureProvider.autoDispose<List<String>>((ref) {
return ref.watch(a);
});
这不是因为autoDispose
。 如果您将代码替换为以下代码,您将再次收到错误:
// Removed "autoDispose"
final a = FutureProvider<List<String>>((ref) {
return Future.value(["test"]);
});
final b = FutureProvider<List<String>>((ref) {
return ref.watch(a);
});
错误:
The argument type 'FutureProvider<List<String>>' can't be assigned to the parameter type 'AlwaysAliveProviderListenable<FutureOr<List<String>>>'.
原因是a
提供者的值是AsyncValue
,因此如果b
提供者直接返回数据,则应该返回AsyncValue<List<String>>
而不是List<String>
。
final a = FutureProvider.autoDispose<List<String>>((ref) {
return Future.value(["test"]);
});
final b = FutureProvider.autoDispose<AsyncValue<List<String>>>((ref) {
return ref.watch(a);
});
或者它可以使用该值并对其进行处理,然后基于该值返回另一个列表,如下所示:
final a = FutureProvider.autoDispose<List<String>>((ref) {
return Future.value(["test"]);
});
final b = FutureProvider.autoDispose<List<String>>((ref) async {
final value = ref.watch(a);
// Doing another operation
await Future.delayed(const Duration(seconds: 2));
return value.maybeWhen(
data: (data) => data.map((e) => 'B $e').toList(),
orElse: () => [],
);
});
发生此错误是因为您尝试在未标记为 .autoDispose 的提供程序中侦听标记为 .autoDispose 的提供程序。
final firstProvider = Provider.autoDispose((ref) => 0);
final secondProvider = Provider((ref) {
// The argument type 'AutoDisposeProvider<int>' can't be assigned to the
// parameter type 'AlwaysAliveProviderBase<Object, Null>'
ref.watch(firstProvider);
});
解决方案是使用 .autoDispose 标记 secondProvider。
final firstProvider = Provider.autoDispose((ref) => 0);
final secondProvider = Provider.autoDispose((ref) {
ref.watch(firstProvider);
});
我只是从页面底部的官方 Riverpod 文档中复制解决方案: https://riverpod.dev/docs/concepts/modifiers/auto_dispose/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.