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
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 (likeActivityRef
) is generated automatically when you run the code generation step (usingflutter pub run build_runner build
).ActivityRef
is aRef
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 namedactivity
, the generatedRef
will beActivityRef
. If for example you define another provider like this: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 namedactivity.dart
,ActivityRef
will be generated in a file calledactivity.g.dart
.You can see an example of this pattern shown in the example project
pub
from the riverpod repository on GitHub. A function calledlikedPackages
is defined inlib/detail.dart
(line 36), and the generated typedefLikedPackagesRef
is defined inlib/detail.g.dart
(line 177).