skip to Main Content

The code below is from the article ‘Make your first provider/network request’ in Riverpod documentation.

//activity.dart
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'activity.dart';

// Necessary for code-generation to work
part 'provider.g.dart';

/// This will create a provider named `activityProvider`
/// which will cache the result of this function.
@riverpod
Future<Activity> activity(ActivityRef ref) async {
  // Using package:http, we fetch a random activity from the Bored API.
  final response = await http.get(Uri.https('boredapi.com', '/api/activity'));
  // Using dart:convert, we then decode the JSON payload into a Map data structure.
  final json = jsonDecode(response.body) as Map<String, dynamic>;
  // Finally, we convert the Map into an Activity instance.
  return Activity.fromJson(json);
}

In the above code, I could not figure out what is ActivityRef and where is it defined?

2

Answers


  1. ActivityRef is an automatically generated reference used by Riverpod for managing the state of providers. It’s generated by the code generation provided by the riverpod_annotation package.

    The ActivityRef is not explicitly defined in the code snippet because it’s generated behind the scenes when you use Riverpod’s code generation mechanism. When you annotate a function with @riverpod, its reference (like ActivityRef) is generated automatically when you run the code generation step (using flutter pub run build_runner build).

    Login or Signup to reply.
  2. ActivityRef is a Ref that is generated by riverpod_generator when you use a code-gen functional provider. The name itself is taken from the name of the function you defined, so because the function in that code is named activity, the generated Ref will be ActivityRef. If for example you define another provider like this:

    @riverpod
    Future<Activity> banana(BananaRef ref) async {
      // ...
    }
    

    As you can see, the name of the ref type should follow the function name, otherwise the code generation will fail.

    This ActivityRef is defined in the generated file as a mixin or typedef, so for example if the provider definition is in a file named activity.dart, ActivityRef will be generated in a file called activity.g.dart.


    You can see an example of this pattern shown in the example project pub from the riverpod repository on GitHub. A function called likedPackages is defined in lib/detail.dart (line 36), and the generated typedef LikedPackagesRef is defined in lib/detail.g.dart (line 177).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search