Annotations
The cornerstone of Riverpod Generator: configuring generated providers using the @riverpod and @Riverpod annotations.
Annotations dictate exactly how a provider behaves, such as managing whether dependencies are disposed, whether the provider accepts parameters, or controlling how long cached data should persist. Riverpod essentially relies on these meta-tags via build_runner.
The @riverpod Shorthand
By default, applying @riverpod generates an AutoDispose provider. This is the recommended approach for most providers.
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'example.g.dart';
// Generates AutoDisposeProvider
@riverpod
String welcomeMessage(WelcomeMessageRef ref) {
return 'Hello, Riverpod Generator!';
}The @Riverpod(keepAlive: true) Annotation
If you want a provider to persist indefinitely (e.g., global configuration, services, app settings) and never auto-dispose, use @Riverpod()with keepAlive explicitly set to true.
@Riverpod(keepAlive: true)
Future<UserPreferences> sharedPrefs(SharedPrefsRef ref) async {
final prefs = await SharedPreferences.getInstance();
return UserPreferences(prefs);
}The dependencies Array
Sometimes for testing or overriding specific global dependencies, Riverpod needs to know exactly which other providers this one depends on explicitly. You can define that in the annotation:
@Riverpod(dependencies: [authServiceProvider])
UserRepository userRepository(UserRepositoryRef ref) {
return UserRepository(ref.watch(authServiceProvider));
}Note on Build Runner Output
The generator automatically handles naming conventions by extracting the camelCase function name or class name, appending `Provider`, and formatting it neatly in the .g.dart file.