Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I use Future<> riverpod example on Flutter?

@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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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;
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading