skip to Main Content
@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), 
    );
  }
}

I am trying to copy the simple example from Riverpod homepage. However, I get

Undefined class 'BoredSuggestionRef'. Try changing the name to the name of an existing class, or creating a class with the name 'BoredSuggestionRef'.

Error and I am trying to build it.

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),
    );
  }

And, in this example, I get 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' error.

How can I use that example in this case?

2

Answers


  1. Try the following code:

    final testingP = FutureProvider.autoDispose<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;
    });
    
    Login or Signup to reply.
  2. The method When is not defined for the type StateProvider, try using a Future provider since you’re awaiting a future response.The code would look like:

    final testingP = FutureProvider<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;
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search