@riverpod
Future<String> boredSuggestion(BoredSuggestionRef ref) async {
final response = await http.get(
Uri.https('https://www.boredapi.com/api/activity'),
);
final json = jsonDecode(response.body) as Map;
return json['activity']! as String;
}
class Home extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final boredSuggestion = ref.watch(boredSuggestionProvider);
// Perform a switch-case on the result to handle loading/error states
return boredSuggestion.when(
loading: () => const Text('loading'),
error: (error, stackTrace) => Text('error: $error'),
data: (data) => Text(data),
);
}
}
我试着从Riverpod主页上复制一个简单的例子。但是,我得到了Undefined class 'BoredSuggestionRef'. Try changing the name to the name of an existing class, or creating a class with the name 'BoredSuggestionRef'.
错误,我正在尝试构建它。
final testingP = StateProvider<Future<String>>((ref) async {
final response = await http.get(
Uri.https('https://www.boredapi.com/api/activity'),
);
final json = jsonDecode(response.body) as Map;
return json['activity']! as String;
});
@override
Widget build(BuildContext context, WidgetRef ref) {
final testing = ref.watch(testingP);
return testing.when(
loading: () => const Text('loading'),
error: (error, stackTrace) => Text('error: $error'),
data: (data) => Text(data),
);
}
在本例中,我得到了The method 'when' isn't defined for the type 'Future'. Try correcting the name to the name of an existing method, or defining a method named 'when'
错误。
在这种情况下,我该如何使用该示例?
2条答案
按热度按时间yrwegjxp1#
请尝试以下代码:
v8wbuo2f2#
没有为StateProvider类型定义When方法,请尝试使用Future提供程序,因为您正在等待将来的响应。代码如下所示: