### Verify riverpod_cli installation and view help Source: https://github.com/rrousselgit/riverpod/blob/master/website/docs/migration/0.13.0_to_0.14.0.mdx Command to verify that the riverpod_cli tool has been successfully installed and display available commands and options for the migration tool. ```shell riverpod --help ``` -------------------------------- ### Fetch Flutter Dependencies Source: https://github.com/rrousselgit/riverpod/blob/master/packages/riverpod_generator/integration/build_yaml/README.md Downloads and installs the required Flutter packages for the Riverpod project. ```bash flutter pub get ``` -------------------------------- ### Install Docusaurus Website Dependencies (Yarn) Source: https://github.com/rrousselgit/riverpod/blob/master/website/README.md This command installs all necessary project dependencies for the Docusaurus website using Yarn. It's the first step to set up the development environment. ```bash $ yarn ``` -------------------------------- ### Run Code Generation and Tests Source: https://github.com/rrousselgit/riverpod/blob/master/packages/riverpod_generator/integration/build_yaml/README.md Executes the build_runner to generate necessary files for the build_yaml example and then runs the Flutter test suite. ```bash cd examples/build_yaml dart run build_runner build flutter test ``` -------------------------------- ### Initialize Code Generation with build_runner Source: https://github.com/rrousselgit/riverpod/blob/master/examples/stackoverflow/README.md Commands to navigate to the stackoverflow example directory and execute the Dart build_runner. This process generates the necessary boilerplate code for Riverpod providers and data models. ```sh cd examples/stackoverflow dart run build_runner build -d ``` -------------------------------- ### Run the Pub example app on Android Source: https://github.com/rrousselgit/riverpod/blob/master/examples/pub/README.md Initializes the Android platform configuration and launches the application. ```bash flutter create . --platforms android flutter run ``` -------------------------------- ### Start Docusaurus Website Local Development Server (Yarn) Source: https://github.com/rrousselgit/riverpod/blob/master/website/README.md This command initiates a local development server for the Docusaurus website, automatically opening a browser window. It supports live reloading, reflecting most changes without server restarts. ```bash $ yarn start ``` -------------------------------- ### Build the Pub example app Source: https://github.com/rrousselgit/riverpod/blob/master/examples/pub/README.md Fetches dependencies and executes code generation using build_runner. ```bash cd examples/pub flutter pub get dart run build_runner build -d ``` -------------------------------- ### Install riverpod_cli migration tool Source: https://github.com/rrousselgit/riverpod/blob/master/website/docs/migration/0.13.0_to_0.14.0.mdx Command to globally activate the riverpod_cli package, which provides automated migration tools for upgrading Riverpod projects to the new syntax introduced in version 0.14.0. ```shell dart pub global activate riverpod_cli ``` -------------------------------- ### Hello world with Dart and Riverpod Source: https://github.com/rrousselgit/riverpod/blob/master/website/docs/introduction/getting_started.mdx Basic Dart-only example using Riverpod. Run with `dart lib/main.dart` to print "Hello world" in the console. ```dart ``` -------------------------------- ### Install global packages with Melos Source: https://github.com/rrousselgit/riverpod/blob/master/examples/pub/README.md Activates Melos globally to manage the multi-package repository. ```bash cd riverpod dart pub global activate melos ``` -------------------------------- ### Hello world with Flutter and Riverpod Source: https://github.com/rrousselgit/riverpod/blob/master/website/docs/introduction/getting_started.mdx Basic Flutter example using Riverpod. Run with `flutter run` to render "Hello world" on your device. ```dart ``` -------------------------------- ### Tick Provider Example Source: https://github.com/rrousselgit/riverpod/blob/master/website/docs/concepts2/refs.mdx A sample provider that updates its state every second using a Timer and demonstrates lifecycle management with ref.onDispose. ```dart @riverpod class Tick extends _$Tick { @override int build() { final timer = Timer.periodic(Duration(seconds: 1), (_) => state++); ref.onDispose(timer.cancel); return 0; } } ``` ```dart final tickProvider = NotifierProvider(Tick.new); class Tick extends Notifier { @override int build() { final timer = Timer.periodic(Duration(seconds: 1), (_) => state++); ref.onDispose(timer.cancel); return 0; } } ``` -------------------------------- ### Install riverpod_lint in analysis_options.yaml Source: https://github.com/rrousselgit/riverpod/blob/master/packages/riverpod_lint/README.md Add the plugin to your project's analysis_options.yaml file to enable linting and refactoring tools. ```yaml plugins: riverpod_lint: ``` -------------------------------- ### Full Riverpod Widget Test Example (Dart) Source: https://github.com/rrousselgit/riverpod/blob/master/website/docs/how_to/testing.mdx Presents a complete example of a Riverpod widget test, demonstrating how to interact with a widget that uses a provider, simulate user input, and assert on both UI and provider state changes. ```dart import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; final counterProvider = StateProvider((ref) => 0); class MyWidget extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final count = ref.watch(counterProvider); return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('Counter')), body: Center( child: Text('$count', key: const Key('counterText')), ), floatingActionButton: FloatingActionButton( onPressed: () => ref.read(counterProvider.notifier).state++, child: const Icon(Icons.add), ), ), ); } } void main() { testWidgets('full widget test example', (tester) async { await tester.pumpWidget( ProviderScope( child: MyWidget(), ), ); // Initial state expect(find.text('0'), findsOneWidget); expect(tester.container().read(counterProvider), 0); // Tap the button await tester.tap(find.byType(FloatingActionButton)); await tester.pump(); // After tapping expect(find.text('1'), findsOneWidget); expect(tester.container().read(counterProvider), 1); }); } ``` -------------------------------- ### Initialize ProviderScope in Flutter Main Source: https://github.com/rrousselgit/riverpod/blob/master/packages/flutter_riverpod/dartdoc/providers.md Demonstrates the required setup to enable Riverpod providers in a Flutter application. ProviderScope must be placed at the root of the widget tree to initialize the provider system. ```dart void main() { runApp(ProviderScope(child: MyApp())); } ``` -------------------------------- ### Install Melos Global Package via Dart Pub Source: https://github.com/rrousselgit/riverpod/blob/master/packages/riverpod_generator/integration/build_yaml/README.md Activates the Melos tool globally using the Dart package manager. Melos is used for managing multi-package repositories like Riverpod. ```bash cd riverpod dart pub global activate melos ``` -------------------------------- ### Start Riverpod Documentation Development Server Source: https://github.com/rrousselgit/riverpod/blob/master/CONTRIBUTING.md Launches the local development server for the Riverpod documentation at localhost:3000. This command starts Docusaurus in development mode, allowing real-time viewing and testing of documentation changes. ```shell yarn dev ``` -------------------------------- ### Implement custom ProviderListenable with SyncProviderTransformerMixin Source: https://github.com/rrousselgit/riverpod/blob/master/website/docs/whats_new.mdx Example of creating a custom `ProviderListenable` using `SyncProviderTransformerMixin` to implement a `where` extension, allowing providers to filter updates based on a custom condition. ```dart final class Where with SyncProviderTransformerMixin { Where(this.source, this.where); @override final ProviderListenable source; final bool Function(T previous, T value) where; @override ProviderTransformer transform( ProviderTransformerContext context, ) { return ProviderTransformer( initState: (_) => context.sourceState.requireValue, listener: (self, previous, next) { if (where(previous, next)) self.state = next; }, ); } } extension on ProviderListenable { ProviderListenable where( bool Function(T previous, T value) where, ) => Where(this, where); } ``` -------------------------------- ### Correct Riverpod Provider and Notifier Definitions Source: https://github.com/rrousselgit/riverpod/blob/master/packages/riverpod_lint/README.md These examples show how to define Riverpod providers and notifiers without directly interacting with 'BuildContext'. ```dart @riverpod int fn(Ref ref) => 0; ``` ```dart @riverpod class MyNotifier extends _$MyNotifier { int build() => 0; void event() {} } ``` -------------------------------- ### Run Riverpod Generator Source: https://github.com/rrousselgit/riverpod/blob/master/packages/riverpod_generator/README.md Execute this command in your terminal to start the `build_runner` and automatically generate Riverpod provider code based on your annotations. ```sh dart run build_runner watch ``` -------------------------------- ### Define Root and Scoped Riverpod Providers Source: https://github.com/rrousselgit/riverpod/blob/master/packages/riverpod_lint/README.md These examples show how to define a basic non-scoped provider and a scoped provider using the 'dependencies' annotation. ```dart // A non-scoped provider @riverpod int root(Ref ref) => 0; ``` ```dart // A possibly scoped provider @Riverpod(dependencies: []) int scoped(Ref ref) => 0; ``` -------------------------------- ### Correct Riverpod Provider Dependency Declarations Source: https://github.com/rrousselgit/riverpod/blob/master/packages/riverpod_lint/README.md These examples demonstrate the correct way to declare provider dependencies, including when to use the 'dependencies' annotation and how to handle scoped providers in widgets. ```dart // No dependencies used, no need to specify "dependencies" @riverpod int example(Ref ref) => 0; ``` ```dart // We can specify an empty "dependencies" list if we wish to. // This marks the provider as "scoped". @Riverpod(dependencies: []) int example(Ref ref) => 0; ``` ```dart @riverpod void example(Ref ref) { // rootProvider is not scoped, no need to specify it as "dependencies" ref.watch(rootProvider); } ``` ```dart @Riverpod(dependencies: [scoped]) void example(Ref ref) { // scopedProvider is scoped and as such specifying "dependencies" is required. ref.watch(scopedProvider); } ``` ```dart // For non-provider objects that use scoped providers, we can use `@Dependencies` // for similar purposes. @Dependencies([scoped]) class BookView extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final selectedBookID = ref.watch(scopedProvider); return Text(selectedBookID.toString()); } } ``` ```dart // Alternatively, widgets specifically can opt to override scoped providers // using `ProviderScope`: ProviderScope( overrides: [ scopedProvider.overrideWithValue(42), ], // Even though BookView uses "scopedProvider", the linter won't complain // as we override the provider. child: BookView(), ) ``` -------------------------------- ### Build Docusaurus Website Static Content (Yarn) Source: https://github.com/rrousselgit/riverpod/blob/master/website/README.md This command generates all static content for the Docusaurus website into the `build` directory. The output can then be hosted on any static content hosting service. ```bash $ yarn build ``` -------------------------------- ### Use Riverpod Codegen to Expose ChangeNotifier Provider Source: https://github.com/rrousselgit/riverpod/blob/master/website/docs/from_provider/quickstart.mdx Demonstrates how to expose a ChangeNotifier using Riverpod's @riverpod annotation with code generation. Uses the listenAndDisposeChangeNotifier extension method to properly manage the notifier lifecycle during the migration phase. ```dart // ignore_for_file: unsupported_provider_value @riverpod MyNotifier example(Ref ref) { return ref.listenAndDisposeChangeNotifier(MyNotifier()); } ``` -------------------------------- ### Define Scoped and Root Providers for Override Examples Source: https://github.com/rrousselgit/riverpod/blob/master/packages/riverpod_lint/README.md These providers are used to demonstrate correct and incorrect overriding practices within ProviderScope based on their dependency declarations. ```dart @Riverpod(dependencies: []) int scoped(Ref ref) => 0; ``` ```dart @riverpod int root(Ref ref) => 0; ``` -------------------------------- ### Configure riverpod_lint in analysis_options.yaml Source: https://github.com/rrousselgit/riverpod/blob/master/website/docs/introduction/getting_started.mdx Enable the riverpod_lint plugin to get lint rules and custom refactoring options for better Riverpod code quality. ```yaml plugins: riverpod_lint: ``` -------------------------------- ### Override NotifierProvider build method (codegen & raw) Source: https://github.com/rrousselgit/riverpod/blob/master/website/docs/whats_new.mdx Demonstrates how to mock only the `Notifier.build` method for a `NotifierProvider` using `overrideWithBuild`, allowing specific initial states while retaining original notifier logic. Includes both code-generated and raw Riverpod examples. ```dart @riverpod class MyNotifier extends _$MyNotifier { @override int build() => 0; void increment() { state++; } } void main() { final container = ProviderContainer.test( overrides: [ myProvider.overrideWithBuild((ref, self) { // Mock the build method to start at 42. // The "increment" method is unaffected. return 42; }), ], ); } ``` ```dart class MyNotifier extends Notifier { @override int build() => 0; void increment() { state++; } } final myProvider = NotifierProvider(MyNotifier.new); void main() { final container = ProviderContainer.test( overrides: [ myProvider.overrideWithBuild((ref, self) { // Mock the build method to start at 42. // The "increment" method is unaffected. return 42; }), ], ); } ``` -------------------------------- ### Define a dependent provider and a widget that reads it Source: https://github.com/rrousselgit/riverpod/blob/master/website/docs/whats_new.mdx This example shows a provider that watches another provider and a `ConsumerWidget` that reads the dependent provider, illustrating a scenario where provider pausing behavior was inconsistent in Riverpod 2.0. ```dart @riverpod int another(Ref ref) { ref.keepAlive(); return ref.watch(exampleProvider); } class MyWidget extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { return Button( onPressed: () { ref.read(anotherProvider); }, child: Text('Click me'), ); } } ``` ```dart final anotherProvider = Provider((ref) { return ref.watch(exampleProvider); }); class MyWidget extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { return Button( onPressed: () { ref.read(anotherProvider); }, child: Text('Click me'), ); } } ``` -------------------------------- ### Execute automatic Riverpod project migration Source: https://github.com/rrousselgit/riverpod/blob/master/website/docs/migration/0.13.0_to_0.14.0.mdx Runs the migration tool to analyze the project and suggest syntax changes for Riverpod 0.14.0 compatibility. The tool will prompt for confirmation on each suggested change. ```shell riverpod migrate ``` -------------------------------- ### Define and Consume a Riverpod Generator Provider Source: https://github.com/rrousselgit/riverpod/blob/master/packages/riverpod_generator/README.md This example demonstrates how to define an asynchronous provider using the `@riverpod` annotation and consume its data within a Flutter `Consumer` widget, handling loading and error states. ```dart import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:dio/dio.dart'; part 'my_file.g.dart'; // Using riverpod_generator, we define Providers by annotating functions with @riverpod. // In this example, riverpod_generator will use this function and generate a matching "fetchProductProvider". // The following example would be the equivalent of a "FutureProvider.autoDispose.family" @riverpod Future> fetchProducts(Ref ref, {required int page, int limit = 50}) async { final dio = Dio(); final response = await dio.get('https://my-api/products?page=$page&limit=$limit'); final json = response.data! as List; return json.map((item) => Product.fromJson(item)).toList(); } // Now that we defined a provider, we can then listen to it inside widgets as usual. Consumer( builder: (context, ref, child) { AsyncValue> products = ref.watch(fetchProductProvider(page: 1)); // Since our provider is async, we need to handle loading/error states return products.when( loading: () => CircularProgressIndicator(), error: (err, stack) => Text('error: $err'), data: (products) { return ListView( children: [ for (final product in products) Text(product.name), ], ); }, ); }, ); ``` -------------------------------- ### Start Riverpod Documentation Server with Specific Language Locale Source: https://github.com/rrousselgit/riverpod/blob/master/CONTRIBUTING.md Launches the local development server for a specific language translation (e.g., Japanese). Only one locale can be hosted at a time locally. The -l flag specifies the language code for viewing translated documentation. ```shell yarn dev -l ja ``` -------------------------------- ### Define a Provider for Mocking in Riverpod (Dart) Source: https://github.com/rrousselgit/riverpod/blob/master/website/docs/how_to/testing.mdx Provides an example of a standard Riverpod provider definition. This type of provider is easily mockable in tests without requiring special setup in its declaration. ```dart import 'package:flutter_riverpod/flutter_riverpod.dart'; final myService = Provider((ref) => MyService()); class MyService { String getData() => 'Real Data'; } ``` -------------------------------- ### Correctly Watching Provider State vs. Reading Source: https://github.com/rrousselgit/riverpod/blob/master/website/docs/concepts2/refs.mdx Demonstrates the correct usage of Ref.watch for listening to state changes and contrasts it with the incorrect use of Ref.read for optimization. It also shows how to use Ref.select for granular state observation. ```dart Consumer( builder: (context, ref, _) { // ❌ Don't use "read" as a mean to ignore changes final tick = ref.read(tickProvider); // ✅ Use "watch" to listen to changes. // This shouldn't be a bottle-neck in your apps. Do not over-optimize. final tick = ref.watch(tickProvider); // ✅ Use "select" to only listen to the specific part of the state you care about final isEven = ref.watch( tickProvider.select((tick) => tick.isEven), ); ... }, ); ``` -------------------------------- ### Define StateNotifier class in Dart Source: https://github.com/rrousselgit/riverpod/blob/master/website/docs/migration/0.13.0_to_0.14.0.mdx Creates a custom StateNotifier class that extends StateNotifier with a generic type parameter representing the state model. This is the base class used for the migration examples. ```dart class MyModel {} class MyStateNotifier extends StateNotifier { MyStateNotifier(): super(MyModel()); } ``` -------------------------------- ### Create a new Flutter project Source: https://github.com/rrousselgit/riverpod/blob/master/website/docs/tutorials/first_app.mdx This command initializes a new Flutter application named 'first_app' in the current directory. It sets up the basic project structure and necessary files for a Flutter development environment. ```sh flutter create first_app ``` -------------------------------- ### StateProvider read-only state access - Before migration (Dart) Source: https://github.com/rrousselgit/riverpod/blob/master/website/docs/migration/0.14.0_to_1.0.0.mdx Original StateProvider usage pattern where ref.watch() returns a StateController instance and requires accessing the .state property to get the actual state value. This pattern is deprecated after the StateProvider update. ```dart final provider = StateProvider(...); Consumer( builder: (context, ref, child) { StateController count = ref.watch(provider); return Text('${count.state}'); } ) ``` -------------------------------- ### Implement Resource Disposal on Provider State Destruction - Dart Source: https://github.com/rrousselgit/riverpod/blob/master/packages/flutter_riverpod/dartdoc/providers.md Demonstrates using ref.onDispose() callback to perform cleanup operations when a provider's state is destroyed. This example closes a StreamController when the autoDispose provider state is no longer needed, preventing resource leaks. ```dart final example = StreamProvider.autoDispose((ref) { final streamController = StreamController(); ref.onDispose(() { // Closes the StreamController when the state of this provider is destroyed. streamController.close(); }); return streamController.stream; }); ``` -------------------------------- ### Migrate ChangeNotifier to Notifier in Dart Source: https://github.com/rrousselgit/riverpod/blob/master/website/docs/from_provider/quickstart.mdx Shows the complete migration from ChangeNotifierProvider to the modern Notifier pattern in Riverpod. Replaces the ChangeNotifier base class with Notifier, implements the build method to initialize state, and converts the provider to NotifierProvider. This is the recommended approach for new code and represents the full migration path. ```dart class MyNotifier extends Notifier { @override int build() => 0; void increment() => state++; } final myNotifierProvider = NotifierProvider(MyNotifier.new); ``` -------------------------------- ### Watch and Combine Providers in Dart Source: https://github.com/rrousselgit/riverpod/blob/master/packages/riverpod/dartdoc/providers.md Creates a FutureProvider that depends on another provider using `ref.watch()`. When the watched provider's value changes, the dependent provider automatically re-evaluates. This example watches a city provider to fetch weather data based on the city value. ```dart final cityProvider = Provider((ref) => 'London'); final weatherProvider = FutureProvider((ref) async { // We use `ref.watch` to watch another provider, and we pass it the provider // that we want to consume. Here: cityProvider final city = ref.watch(cityProvider); // We can then use the result to do something based on the value of `cityProvider`. return fetchWeather(city: city); }); ``` -------------------------------- ### Create Reusable Fade-In Logic with Custom Flutter Hook Source: https://github.com/rrousselgit/riverpod/blob/master/website/docs/concepts/about_hooks.mdx This example illustrates how to encapsulate animation logic into a custom reusable hook, `useFadeIn()`. This custom hook abstracts away the details of managing an `AnimationController` and its lifecycle, allowing the fade-in functionality to be easily reused across any `HookWidget` by simply calling `useFadeIn()` to get the current opacity value. ```dart double useFadeIn() { final animationController = useAnimationController( duration: const Duration(seconds: 2), ); useEffect(() { animationController.forward(); return null; }, const []); useAnimation(animationController); return animationController.value; } ``` -------------------------------- ### Implement Fade-In Animation using Flutter HookWidget Source: https://github.com/rrousselgit/riverpod/blob/master/website/docs/concepts/about_hooks.mdx This example shows how to achieve a fade-in animation using a HookWidget and the `flutter_hooks` package. It utilizes `useAnimationController` for automatic controller management, `useEffect` for `initState`-like behavior (starting the animation once), and `useAnimation` to trigger widget rebuilds when the animation updates. This approach results in more concise and declarative code compared to `StatefulWidget`. ```dart class FadeIn extends HookWidget { const FadeIn({Key? key, required this.child}) : super(key: key); final Widget child; @override Widget build(BuildContext context) { // Create an AnimationController. The controller will automatically be // disposed when the widget is unmounted. final animationController = useAnimationController( duration: const Duration(seconds: 2), ); // useEffect is the equivalent of initState + didUpdateWidget + dispose. // The callback passed to useEffect is executed the first time the hook is // invoked, and then whenever the list passed as second parameter changes. // Since we pass an empty const list here, that's strictly equivalent to `initState`. useEffect(() { // start the animation when the widget is first rendered. animationController.forward(); // We could optionally return some "dispose" logic here return null; }, const []); // Tell Flutter to rebuild this widget when the animation updates. // This is equivalent to AnimatedBuilder useAnimation(animationController); return Opacity( opacity: animationController.value, child: child, ); } } ``` -------------------------------- ### Install riverpod_sqflite and sqflite packages Source: https://github.com/rrousselgit/riverpod/blob/master/website/docs/concepts2/offline.mdx Install required dependencies for SQFlite integration with Riverpod. This command adds both the riverpod_sqflite package and the sqflite database package to your Dart project. ```shell dart pub add riverpod_sqflite sqflite ``` -------------------------------- ### Create ChangeNotifierProvider for migration in Dart Source: https://github.com/rrousselgit/riverpod/blob/master/website/docs/from_provider/quickstart.mdx Demonstrates how to wrap an existing ChangeNotifier class with Riverpod's ChangeNotifierProvider for easy migration. This approach allows developers to use Riverpod's provider system while keeping the familiar ChangeNotifier pattern. The provider is created as a final variable that instantiates the MyNotifier class through a callback function. ```dart // If you have this... class MyNotifier extends ChangeNotifier { int state = 0; void increment() { state++; notifyListeners(); } } // ... just add this! final myNotifierProvider = ChangeNotifierProvider((ref) { return MyNotifier(); }); ``` -------------------------------- ### Install Riverpod Documentation Dependencies with Yarn Source: https://github.com/rrousselgit/riverpod/blob/master/CONTRIBUTING.md Installs required Node.js dependencies for the Riverpod documentation project. This command uses Yarn package manager to download and configure all packages needed to build and run the Docusaurus-based documentation website locally. ```shell yarn install ``` -------------------------------- ### Deploy Docusaurus Website to GitHub Pages (Yarn) Source: https://github.com/rrousselgit/riverpod/blob/master/website/README.md This command builds the Docusaurus website and pushes the generated content to the `gh-pages` branch, specifically designed for GitHub Pages hosting. Users need to replace `` with their actual GitHub username. ```bash $ GIT_USER= USE_SSH=true yarn deploy ``` -------------------------------- ### CONSIDER Initializing Riverpod Providers on User Interaction Source: https://github.com/rrousselgit/riverpod/blob/master/website/docs/root/do_dont.mdx When provider initialization logic depends on external factors, such as user input or navigation, it's often best to trigger it in response to a user action, like a button press. This ensures the initialization occurs at the appropriate time and context. ```dart ElevatedButton( onPressed: () { ref.read(provider).init(); Navigator.of(context).push(...); }, child: Text('Navigate'), ) ``` -------------------------------- ### Install Riverpod Generator Dependencies Source: https://github.com/rrousselgit/riverpod/blob/master/packages/riverpod_generator/README.md Add `riverpod_annotation` to your project's dependencies and `build_runner` along with `riverpod_generator` to your development dependencies in `pubspec.yaml`. ```yaml dependencies: # or flutter_riverpod/hooks_riverpod as per https://riverpod.dev/docs/introduction/getting_started riverpod: # the annotation package containing @riverpod riverpod_annotation: dev_dependencies: # a tool for running code generators build_runner: # the code generator riverpod_generator: ``` -------------------------------- ### Create ChangeNotifier Extension for Codegen in Dart Source: https://github.com/rrousselgit/riverpod/blob/master/website/docs/from_provider/quickstart.mdx Defines a Dart extension method on Ref that enables code generation support for ChangeNotifier instances. This utility handles listener management and disposal lifecycle, bridging the gap until full migration to Notifier is complete. ```dart extension ChangeNotifierWithCodeGenExtension on Ref { T listenAndDisposeChangeNotifier(T notifier) { notifier.addListener(notifyListeners); onDispose(() => notifier.removeListener(notifyListeners)); onDispose(notifier.dispose); return notifier; } } ``` -------------------------------- ### Using ProviderContainer in pure Dart applications Source: https://github.com/rrousselgit/riverpod/blob/master/website/docs/concepts2/containers.mdx Demonstrates how to create and use a ProviderContainer in a pure Dart environment, such as command-line or server-side applications, including listening to provider changes and disposing the container. ```dart import 'package:riverpod/riverpod.dart'; void main() { final container = ProviderContainer(); try { final sub = container.listen(counterProvider, (previous, next) { print('Counter changed from $previous to $next'); }); print('Counter starts at ${sub.read()}'); } finally { // Dispose the container when done container.dispose(); } } ``` -------------------------------- ### Configure the main Flutter application with HomeView Source: https://github.com/rrousselgit/riverpod/blob/master/website/docs/tutorials/first_app.mdx This Dart code sets up the entry point for the Flutter application, `main()`, which runs the `MyApp` widget. `MyApp` is a `StatelessWidget` that defines the root `MaterialApp` and sets `HomeView` as its initial screen. It integrates the previously defined `home.dart` into the application's widget tree. ```dart import 'package:flutter/material.dart'; import 'home.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp(home: HomeView()); } } ``` -------------------------------- ### Incorrect Provider Overrides in Non-Root ProviderScope Source: https://github.com/rrousselgit/riverpod/blob/master/packages/riverpod_lint/README.md This example demonstrates an incorrect attempt to override a non-scoped provider ('rootProvider') in a ProviderScope that is not the root of the widget tree. ```dart class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return ProviderScope( // This ProviderScope is not the root one, so only providers with "dependencies" // can be specified. overrides: [ // rootProvider does not specify "dependencies" and therefore should not // be overridden here. rootProvider.overrideWith(...), ], child: Container(), ); } } ``` -------------------------------- ### Example of a modifiable state variable Source: https://github.com/rrousselgit/riverpod/blob/master/website/docs/concepts2/providers.mdx This snippet demonstrates a publicly accessible and modifiable variable, analogous to the 'modifiable' behavior of Riverpod's Notifier providers. ```dart // Anything can modify "state" var state = 0; ``` -------------------------------- ### Incorrect vs. Correct Notifier Initialization Source: https://github.com/rrousselgit/riverpod/blob/master/website/docs/concepts2/providers.mdx Illustrates the incorrect way to initialize state in a Notifier's constructor and the correct way using the 'build' method, as 'ref' is not yet available in the constructor. ```dart class MyNotifier extends ... { MyNotifier() { // ❌ Don't do this // This will throw an exception state = AsyncValue.data(42); } @override Future build() { // ✅ Do this instead state = AsyncValue.data(42); } } ``` -------------------------------- ### Define Main Application Entry Point (Dart) Source: https://github.com/rrousselgit/riverpod/blob/master/website/docs/how_to/cancel.mdx This code sets up the basic Flutter application structure, including the `ProviderScope` widget at the root. The `ProviderScope` is crucial for Riverpod providers to be accessible throughout the widget tree, ensuring proper state management. ```dart import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'detail_screen.dart'; void main() { runApp( const ProviderScope( child: MyApp(), ), ); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('Home')), body: Center( child: ElevatedButton( child: const Text('Go to detail'), onPressed: () { Navigator.of(context).push( MaterialPageRoute( builder: (context) { return const DetailScreen(); }, ), ); }, ), ), ), ); } } ``` -------------------------------- ### Incorrect Riverpod Provider and Notifier Definitions with BuildContext Source: https://github.com/rrousselgit/riverpod/blob/master/packages/riverpod_lint/README.md These examples demonstrate incorrect practices where 'BuildContext' is directly used as a parameter in a provider function or a notifier method. ```dart // Providers should not receive a BuildContext as a parameter. int fn(Ref ref, BuildContext context) => 0; ``` ```dart @riverpod class MyNotifier extends _$MyNotifier { int build() => 0; // Notifiers should not have methods that receive a BuildContext as a parameter. void event(BuildContext context) {} } ``` -------------------------------- ### Implement "Search as You Type" with Riverpod FutureProvider (Dart/Flutter) Source: https://github.com/rrousselgit/riverpod/blob/master/website/i18n/bn/docusaurus-plugin-content-docs/current/cookbooks/search_as_we_type.mdx This comprehensive Dart/Flutter example demonstrates building a full "search as you type" feature using Riverpod. It utilizes `StateProvider` (`searchFieldProvider`) to manage the search input and `FutureProvider` (`questionsProvider`) to fetch data from the StackExchange API based on the input. The `questionsProvider` debounces requests by watching the `searchFieldProvider` and handles loading, error, and data states for display in a `ListView`. ```dart import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; final searchFieldProvider = StateProvider((ref) => ''); final questionsProvider = FutureProvider((ref) async { final client = http.Client(); ref.onDispose(client.close); final search = ref.watch(searchFieldProvider); Uri uri; if (search.isEmpty) { uri = Uri.parse( 'https://api.stackexchange.com/2.3/questions?order=desc&sort=activity&site=stackoverflow', ); } else { final encodedQuery = Uri.encodeComponent(search); uri = Uri.parse( 'https://api.stackexchange.com/2.3/search?order=desc&sort=activity&intitle=$encodedQuery&site=stackoverflow', ); } final response = await client.get(uri); final questions = jsonDecode(response.body); return questions['items'].map((question) => question['title']).toList(); }); void main() => runApp(const ProviderScope(child: MyApp())); class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return const MaterialApp(home: MyHomePage()); } } class MyHomePage extends ConsumerWidget { const MyHomePage({Key? key}) : super(key: key); @override Widget build(BuildContext context, WidgetRef ref) { final questions = ref.watch(questionsProvider); return Scaffold( appBar: AppBar(title: const Text('Questions')), body: Column( children: [ TextField( onChanged: (value) => ref.read(searchFieldProvider.notifier).state = value, ), Expanded( child: questions.when( loading: () => const Center(child: CircularProgressIndicator()), error: (error, stack) => Center(child: Text('Error $error')), data: (questions) { return ListView.builder( itemCount: questions.length, itemBuilder: (context, index) { final question = questions[index]; return ListTile( title: Text( question.toString(), ), ); }, ); }, ), ), ], ), ); } } ``` -------------------------------- ### Correct Provider Overrides in Riverpod ProviderScope Source: https://github.com/rrousselgit/riverpod/blob/master/packages/riverpod_lint/README.md These examples show how to correctly override providers in a ProviderScope, distinguishing between root and non-root scopes regarding providers without 'dependencies'. ```dart void main() { runApp( ProviderScope( // This is the main ProviderScope. All providers can be overridden there overrides: [ rootProvider.overrideWith(...), scopedProvider.overrideWith(...), ], child: MyApp(), ), ); } ``` ```dart class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return ProviderScope( // This ProviderScope is not the root one, so only providers with "dependencies" // can be specified. overrides: [ scopedProvider.overrideWith(...), ], child: Container(), ); } } ``` -------------------------------- ### Illustrate synchronous, Future, and Stream functions Source: https://github.com/rrousselgit/riverpod/blob/master/website/docs/concepts2/providers.mdx This snippet demonstrates the basic Dart syntax for synchronous functions, asynchronous functions returning a Future, and functions returning a Stream, corresponding to Riverpod's provider types. ```dart int synchronous() => 0; Future future() async => 0; Stream stream() => Stream.value(0); ``` -------------------------------- ### Migrate to Riverpod Notifier with Codegen in Dart Source: https://github.com/rrousselgit/riverpod/blob/master/website/docs/from_provider/quickstart.mdx Shows the final migrated state after transitioning from ChangeNotifierProvider to Riverpod's modern Notifier pattern. The @riverpod class annotation replaces the temporary extension, eliminating migration-related boilerplate and providing a cleaner, future-proof API. ```dart @riverpod class MyNotifier extends _$MyNotifier { @override int build() => 0; void increment() => state++; } ``` -------------------------------- ### Define a Riverpod FutureProvider for user data Source: https://github.com/rrousselgit/riverpod/blob/master/website/docs/concepts2/providers.mdx This snippet shows how to define a FutureProvider in Riverpod, which automatically caches the result of an asynchronous operation. It includes both code-generated and raw syntax examples. ```dart // The equivalent of our fetchUser function, but the result is cached. // This will generate a "userProvider". Using it multiple times will // return the same value. @riverpod Future user(Ref ref) async { final response = await http.get('https://api.example.com/user/123'); return User.fromJson(response.body); } ``` ```dart // The equivalent of our fetchUser function, but the result is cached. // Using userProvider multiple times will return the same value. final userProvider = FutureProvider((ref) async { final response = await http.get('https://api.example.com/user/123'); return User.fromJson(response.body); }); ``` -------------------------------- ### Incorrect Riverpod Provider Dependency Declarations Source: https://github.com/rrousselgit/riverpod/blob/master/packages/riverpod_lint/README.md These examples illustrate common mistakes in declaring provider dependencies, such as listing unused dependencies, omitting required dependencies, or listing non-scoped providers. ```dart // scopedProvider isn't used and should therefore not be listed @Riverpod(dependencies: [scoped]) int example(Ref ref) => 0; ``` ```dart @Riverpod(dependencies: []) void example(Ref ref) { // scopedProvider is used but not present in the list of dependencies ref.watch(scopedProvider); } ``` ```dart @Riverpod(dependencies: [root]) void example(Ref ref) { // rootProvider is not a scoped provider. As such it shouldn't be listed in "dependencies" ref.watch(rootProvider); } ``` ```dart class BookView extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { // If a function/class uses a scoped provider, they must specify `@Dependencies` final selectedBookID = ref.watch(scopedProvider); return Text(selectedBookID.toString()); } } ``` -------------------------------- ### Configure riverpod_generator Naming Conventions (YAML) Source: https://github.com/rrousselgit/riverpod/blob/master/packages/riverpod_generator/README.md This `build.yaml` configuration demonstrates how to customize the naming conventions for generated providers, including prefixes, suffixes, and strip patterns. These options control how `riverpod_generator` names your providers. ```yaml targets: $default: builders: riverpod_generator: options: # Could be changed to "my", such that riverpod_generator # would generate "myCountProvider" instead of "countProvider" provider_name_prefix: "" # (default) # Similar to provider_name_prefix, this is an option for renaming # providers with parameters ("families"). # This takes precedence over provider_name_prefix. provider_family_name_prefix: "" # (default) # Could be changed to "Pod", such that riverpod_generator # would generate "countPod" instead of "countProvider" provider_name_suffix: "Provider" # (default) # Similar to provider_name_suffix, this is an option for renaming # providers with parameters ("families"). # This takes precedence over provider_name_suffix. provider_family_name_suffix: "Provider" # (default) # A regular expression that riverpod_generator will # remove from generated providers names. # The following regex removes the trailing `Notifier` from # the name of generated providers. # Given a class named `CounterNotifier`, Riverpod will # remove any text matching the regex (so here `Notifier`). # We end-up with `Counter` ; which is then transformed to `counterProvider` provider_name_strip_pattern: "Notifier$" # (default) ```