### Implementation example Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/ConsumerWidget/createState.html An example of how the createState method is implemented within the ConsumerWidget itself. ```APIDOC ## Implementation ### Code ```dart @override // ignore: library_private_types_in_public_api _ConsumerState createState() => _ConsumerState(); ``` ``` -------------------------------- ### ConsumerWidget Usage Example Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/ConsumerWidget-class.html This example demonstrates how to subclass ConsumerWidget and use ref.watch to listen to a provider within the build method. ```APIDOC ## ConsumerWidget ### Description The equivalent of a StatelessWidget that can listen to providers. Using ConsumerWidget, this allows the widget tree to listen to changes on provider, so that the UI automatically updates when needed. Do not modify any state or start any http request inside build. ### Example ```dart final helloWorldProvider = Provider((_) => 'Hello world'); class Example extends ConsumerWidget { const Example({Key? key}): super(key: key); @override Widget build(BuildContext context, WidgetRef ref) { final value = ref.watch(helloWorldProvider); return Text(value); // Hello world } } ``` ### Multiple Providers Note: You can watch as many providers inside build as you want to: ```dart @override Widget build(BuildContext context, WidgetRef ref) { final value = ref.watch(someProvider); final another = ref.watch(anotherProvider); return Text(value); // Hello world } ``` ### Constructors #### ConsumerWidget ```dart ConsumerWidget({Key? key}) ``` ### Methods #### build ```dart build(BuildContext context, WidgetRef ref) → Widget ``` Describes the part of the user interface represented by this widget. ``` -------------------------------- ### StreamProvider Usage Example Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/StreamProvider-class.html An example demonstrating how to create and use a StreamProvider to listen to WebSocket messages. ```APIDOC ## StreamProvider Usage Example ### Description This example shows how to create a `StreamProvider` to connect to a WebSocket and display incoming messages in the UI. ### Provider Creation ```dart import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:web_socket_channel/web_socket_channel.dart'; final messageProvider = StreamProvider.autoDispose((ref) async* { // Connect to the WebSocket final channel = WebSocketChannel.connect(Uri.parse('ws://echo.websocket.org')); // Close the connection when the stream is destroyed ref.onDispose(() => channel.sink.close()); // Emit values received from the stream await for (final value in channel.stream) { yield value.toString(); } }); ``` ### UI Integration ```dart import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; Widget build(BuildContext context, WidgetRef ref) { // Watch the stream provider for updates final AsyncValue message = ref.watch(messageProvider); return message.when( loading: () => const CircularProgressIndicator(), error: (err, stack) => Text('Error: $err'), data: (message) { return Text(message); }, ); } ``` ### Notes * Use `StreamProvider.autoDispose` for resources like WebSockets or Firebase connections to ensure they are cleaned up when no longer needed. * By default, `StreamProvider` instances are not destroyed, which can lead to resource leaks if not managed properly. ``` -------------------------------- ### StreamProvider Usage Example Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/StreamProvider/StreamProvider.html This example demonstrates how to create a StreamProvider that connects to a WebSocket and emits received messages. The UI then watches this provider to display the messages. ```APIDOC ```dart final messageProvider = StreamProvider.autoDispose((ref) async* { // Open the connection final channel = IOWebSocketChannel.connect('ws://echo.websocket.org'); // Close the connection when the stream is destroyed ref.onDispose(() => channel.sink.close()); // Parse the value received and emit a Message instance await for (final value in channel.stream) { yield value.toString(); } }); Widget build(BuildContext context, WidgetRef ref) { AsyncValue message = ref.watch(messageProvider); return message.when( loading: () => const CircularProgressIndicator(), error: (err, stack) => Text('Error: $err'), data: (message) { return Text(message); }, ); } ``` ``` -------------------------------- ### Example Usage Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/legacy/StateNotifierProvider/StateNotifierProvider.html Demonstrates how to define and use a StateNotifierProvider with a StateNotifier to manage a list of todos. ```APIDOC ## Example Usage ### Define a StateNotifier ```dart class TodosNotifier extends StateNotifier> { TodosNotifier(): super([]); void add(Todo todo) { state = [...state, todo]; } void remove(String todoId) { state = [ for (final todo in state) if (todo.id != todoId) todo, ]; } void toggle(String todoId) { state = [ for (final todo in state) if (todo.id == todoId) todo.copyWith(completed: !todo.completed), ]; } } ``` ### Create a StateNotifierProvider ```dart final todosProvider = StateNotifierProvider>((ref) => TodosNotifier()); ``` ### Interact with the provider in the UI ```dart Widget build(BuildContext context, WidgetRef ref) { // rebuild the widget when the todo list changes List todos = ref.watch(todosProvider); return ListView( children: [ for (final todo in todos) CheckboxListTile( value: todo.completed, // When tapping on the todo, change its completed status onChanged: (value) => ref.read(todosProvider.notifier).toggle(todo.id), title: Text(todo.description), ), ], ); } ``` ``` -------------------------------- ### LoggingMixin Example for runBuild Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/AnyNotifier/runBuild.html Implement a mixin to log state changes before and after the build method of a notifier. This example demonstrates how to override runBuild to include custom logging logic. ```dart mixin LoggingMixin on AnyNotifier { @override void runBuild() { print('Will build $this'); super.runBuild(); print('Did build $this'); } } ``` -------------------------------- ### Usage Example: Correct Usage in build method Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/WidgetRef/listen.html Demonstrates the correct way to use `ref.listen` at the root of the `build` method. ```dart class Example extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { // Correct: ref.listen is at the root of the build method. ref.listen>(someProvider, (previous, next) { // Handle state changes imperatively if (next.hasError) { print('Error: ${next.error}'); } else if (next.value != null) { print('Data updated: ${next.value}'); } }); // Other widget build logic... return Text('Listening to provider...'); } } ``` -------------------------------- ### FutureProvider Usage Example Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/FutureProvider-class.html Demonstrates how to create and use a FutureProvider to fetch and display configuration data, handling loading, error, and data states. ```APIDOC ## Usage Example: Reading a Configuration File ### Creating the Provider ```dart final configProvider = FutureProvider((ref) async { final content = json.decode( await rootBundle.loadString('assets/configurations.json'), ) as Map; return Configuration.fromJson(content); }); ``` ### Reading from the UI ```dart Widget build(BuildContext context, WidgetRef ref) { AsyncValue config = ref.watch(configProvider); return config.when( loading: () => const CircularProgressIndicator(), error: (err, stack) => Text('Error: $err'), data: (config) { return Text(config.host); }, ); } ``` ### Description This example shows how to create a `FutureProvider` to load a configuration file asynchronously. The UI then uses `ref.watch` to obtain an `AsyncValue` and renders different UI states based on whether the data is loading, has an error, or is available. ``` -------------------------------- ### SyncProviderTransformerMixin Usage Example Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/misc/SyncProviderTransformerMixin-mixin.html This example demonstrates how to use the SyncProviderTransformerMixin to create a custom provider that filters values based on a condition. It shows the implementation of the `Where` class and the `where` extension method on `ProviderListenable`. ```APIDOC ## SyncProviderTransformerMixin mixin A mixin for custom ProviderListenables that do not emit AsyncValue. If in error state, an exception will happen when trying to read the state of this listenable. ### Usage To use this mixin, you must implement the `transform` method, along with the `source` getter. The `source` will be the original provider that you are transforming. And `transform` is where your transformation logic will be defined. The following example implements a variable of ProviderListenableSelect.select, where the callback returns a boolean instead of the selected value. ```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); } ``` Used as `ref.watch(provider.where((previous, value) => value > 0))`. See also: * ProviderTransformer, the object responsible for the transformation logic. ``` -------------------------------- ### Example Usage of selectAsync Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/StreamProvider/selectAsync.html Demonstrates how to use selectAsync to combine two asynchronous providers, where one depends on the result of the other. ```APIDOC ## Example Usage ```dart // A provider which asynchronously loads configurations, which may change over time. final configsProvider = StreamProvider((ref) async { // TO-DO fetch the configurations, such as by using Firebase }); // A provider which fetches a list of products based on the configurations. final productsProvider = FutureProvider((ref) async { // We obtain the host from the configs, while ignoring changes to other properties. // As such, the productsProvider will rebuild only if the host changes. final host = await ref.watch(configsProvider.selectAsync((config) => config.host)); return http.get('$host/products'); }); ``` ``` -------------------------------- ### Usage Example Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/Ref/onDispose.html Demonstrates the preferred way to use multiple onDispose calls for different disposable objects. ```APIDOC ## Usage Example ### Description This example shows the recommended pattern for using `onDispose` by registering separate dispose callbacks for each disposable resource. ### Code ```dart // Good: final disposable1 = Disposable(...); ref.onDispose(disposable1.dispose); final disposable2 = Disposable(...); ref.onDispose(disposable2.dispose); ``` ### Bad Example (for comparison) ```dart // Bad: final disposable1 = Disposable(...); final disposable2 = Disposable(...); ref.onDispose(() { disposable1.dispose(); disposable2.dispose(); }); ``` ### Rationale Using multiple `onDispose` calls makes it easier to track if a dispose is missing for a given object and prevents potential memory leaks if an exception occurs during the disposal process. ``` -------------------------------- ### LoggingMixin example for runBuild Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/AsyncNotifier/runBuild.html Demonstrates how to use a mixin to log state changes before and after the build method is executed. This mixin can be applied to any notifier. ```dart mixin LoggingMixin on AnyNotifier { @override void runBuild() { print('Will build $this'); super.runRunBuild(); print('Did build $this'); } } ``` -------------------------------- ### ConsumerState Usage Example Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/ConsumerState-class.html Demonstrates how to use ConsumerState with a ConsumerStatefulWidget, accessing providers within the build method. ```APIDOC ## ConsumerState Usage Example ### Description This example shows how to create a `ConsumerStatefulWidget` and its corresponding `ConsumerState`. The `ConsumerState` class provides a `ref` property that can be used to interact with Riverpod providers, such as reading their values in the `build` method. ### Code ```dart class MyConsumer extends ConsumerStatefulWidget { const MyConsumer({Key? key}): super(key: key); @override ConsumerState createState() => _MyConsumerState(); } class _MyConsumerState extends ConsumerState { @override void initState() { // All State life-cycles can be used super.initState(); } @override Widget build(BuildContext context) { // "ref" is a property of ConsumerState and can be used to read providers ref.watch(someProvider); // ... rest of the widget build return Container(); // Placeholder } } ``` ### Key Features - Extends `State` with a `ref` property. - Integrates with `ConsumerStatefulWidget`. - Allows provider access within `State` lifecycle methods. ``` -------------------------------- ### Usage Example: Correct Usage within a Builder Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/WidgetRef/listen.html Shows how `ref.listen` can be correctly used inside a builder function (e.g., `ListView.builder`). ```dart class Example extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { return ListView.builder( itemCount: 10, itemBuilder: (context, index) { // Correct: ref.listen is at the root of the itemBuilder builder. ref.listen(counterProvider, (previous, next) { print('Counter changed to: $next'); }); return ListTile(title: Text('Item $index')); }, ); } } ``` -------------------------------- ### LoggingMixin Example for runBuild Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/Notifier/runBuild.html Demonstrates how to use a mixin to log state changes before and after the build method using runBuild. This mixin can be applied to any notifier. ```dart mixin LoggingMixin on AnyNotifier { @override void runBuild() { print('Will build $this'); super.runRunBuild(); print('Did build $this'); } } ``` -------------------------------- ### Basic ProviderScope Setup Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/ProviderScope/ProviderScope.html Wrap your entire application with ProviderScope to enable Riverpod. This should be done at the root of your widget tree. ```dart void main() { runApp( // Enabled Riverpod for the entire application ProviderScope( child: MyApp(), ), ); } ``` -------------------------------- ### runBuild Method Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/AnyNotifier-class.html Executes the build logic for the notifier, typically overridden to perform setup or initialization. ```APIDOC ## runBuild Method ### Description Executes Notifier.build. ### Method - **runBuild**() → void ``` -------------------------------- ### Example: Counter Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/legacy/StateNotifier-class.html Demonstrates how to subclass StateNotifier to manage a counter's state. ```APIDOC ## Example: Counter ### Subclassing StateNotifier ```dart class Counter extends StateNotifier { Counter(): super(0); void increment() => state++; void decrement() => state--; } ``` ### Explanation - The `Counter` class extends `StateNotifier`, specifying that it will manage an integer state. - The constructor `Counter(): super(0);` initializes the `StateNotifier` with an initial state of `0`. - The `increment` and `decrement` methods modify the `state` property. Assigning a new value to `state` automatically notifies listeners. - This `StateNotifier` can then be used with `StateNotifierBuilder` or `StateNotifierProvider` from `package:flutter_state_notifier` or `package:riverpod` to update the UI. ``` -------------------------------- ### Defining a Future Provider Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/Consumer-class.html Example of how to define a Future provider that fetches user data. ```dart @riverpod Future fetchUser(Ref ref) async { // ... } ``` -------------------------------- ### overrideWithValue Usage Example Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/StreamProvider/overrideWithValue.html An example demonstrating how to use overrideWithValue to provide a ThemeData to a provider. ```APIDOC final themeProvider = Provider((ref) => throw UnimplementedError()); MaterialApp( builder: (context, child) { final theme = Theme.of(context); return ProviderScope( overrides: [ themeProvider.overrideWithValue(theme), ], child: MyApp(), ); }, ); ``` -------------------------------- ### Consumer build method implementation example Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/Consumer/build.html A typical implementation of the build method for a Consumer widget, which utilizes a builder function to construct the UI. ```APIDOC ## Implementation Example ### Description This shows a common way to implement the `build` method within a `Consumer` widget, often delegating the UI construction to a separate `builder` function. ### Code ```dart @override Widget build(BuildContext context, WidgetRef ref) { return builder(context, ref, child); } ``` ### Parameters - **context** (BuildContext) - The build context. - **ref** (WidgetRef) - The widget reference. - **child** (Widget) - An optional child widget that can be passed down. ### Returns - **Widget** - The widget returned by the `builder` function. ``` -------------------------------- ### ConsumerWidget Example Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/Consumer/Consumer.html Demonstrates the typical usage of a ConsumerWidget to watch a provider and display its value. This approach rebuilds the entire widget when the provider changes. ```dart @riverpod Future fetchUser(Ref ref) async { // ... } class Example extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { return Scaffold( appBar: AppBar(title: Text('User')), body: switch (ref.watch(userProvider) { AsyncValue(:final value?) => Text(value.name), AsyncValue(hasError: true) => Text('Error'), _ => CircularProgressIndicator(), }, } } ``` -------------------------------- ### Example Usage of overrideWith Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/legacy/StateProvider/overrideWith.html Demonstrates how to use `overrideWith` within `ProviderScope.overrides` to replace a provider's implementation, for instance, with a fake service during testing. ```APIDOC final myService = Provider((ref) => MyService()); runApp( ProviderScope( overrides: [ myService.overrideWith((ref) { ref.watch('other'); return MyFakeService(); }) ], child: MyApp(), ), ); ``` -------------------------------- ### FutureProvider Family for Message Fetching Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/FutureProvider/family-constant.html A `FutureProvider.family` example for fetching messages by ID asynchronously. It demonstrates the correct syntax for watching a family provider with a parameter. ```dart final messagesFamily = FutureProvider.family((ref, id) async { return dio.get('http://my_api.dev/messages/$id'); }); ``` ```dart Widget build(BuildContext context, WidgetRef ref) { final response = ref.watch(messagesFamily('id')); } ``` -------------------------------- ### Provider Family with Locale Example Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/FutureProvider/family-constant.html Demonstrates a `Provider.family` that returns a String based on a Locale parameter. It's useful for internationalization or theming. ```dart final titleFamily = Provider.family((ref, locale) { if (locale == const Locale('en')) { return 'English title'; } else if (locale == const Locale('fr')) { return 'Titre Français'; } }); ``` ```dart @override Widget build(BuildContext context, WidgetRef ref) { final locale = Localizations.localeOf(context); // Obtains the title based on the current Locale. // Will automatically update the title when the Locale changes. final title = ref.watch(titleFamily(locale)); return Text(title); } ``` -------------------------------- ### Sorting a todo-list with watch Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/Ref/watch.html This example demonstrates how to use `watch` to create a derived provider that sorts a list of todos based on a sort order and the unsorted list itself. The sorted list is recomputed only when either the sort order or the unsorted list changes. ```dart final sortProvider = StateProvider((_) => Sort.byName); final unsortedTodosProvider = StateProvider((_) => []); final sortedTodosProvider = Provider((ref) { // listen to both the sort enum and the unfiltered list of todos final sort = ref.watch(sortProvider); final todos = ref.watch(unsortedTodosProvider); // Creates a new sorted list from the combination of the unfiltered // list and the filter type. return [...todos].sort((a, b) { ... }); }); ``` -------------------------------- ### Implementing a Custom Provider Transformation with SyncProviderTransformerMixin Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/misc/SyncProviderTransformerMixin-mixin.html This example shows how to implement a custom provider transformation using `SyncProviderTransformerMixin`. It defines a `Where` class that filters values from a source provider based on a condition. This is useful for creating derived providers that only update when a specific condition is met. ```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); } ``` -------------------------------- ### StateT Update Method Example Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/legacy/StateController/update.html Compares the syntax for updating state directly versus using the update method. The update method is preferred when the new state depends on the previous state. ```dart ref.read(provider.notifier).state = ref.read(provider.notifier).state + 1; ``` ```dart ref.read(provider.notifier).update((state) => state + 1); ``` -------------------------------- ### Interact with ChangeNotifierProvider in the UI Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/legacy/ChangeNotifierProvider/ChangeNotifierProvider.html Watch the provider to get the current state and read the notifier to call its methods. This example shows how to display a list of todos and toggle their completion status. ```dart Widget build(BuildContext context, WidgetRef ref) { // rebuild the widget when the todo list changes List todos = ref.watch(todosProvider).todos; return ListView( children: [ for (final todo in todos) CheckboxListTile( value: todo.completed, // When tapping on the todo, change its completed status onChanged: (value) => ref.read(todosProvider.notifier).toggle(todo.id), title: Text(todo.description), ), ], ); } ``` -------------------------------- ### Use-case example: Sorting a todo-list Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/Ref/watch.html Demonstrates how `watch` can be used to create a derived state (sorted todos) that automatically updates when its dependencies (unsorted todos or sort order) change. This avoids expensive computations in the UI and ensures efficient re-computation only when necessary. ```dart final sortProvider = StateProvider((_) => Sort.byName); final unsortedTodosProvider = StateProvider((_) => []); final sortedTodosProvider = Provider((ref) { // listen to both the sort enum and the unfiltered list of todos final sort = ref.watch(sortProvider); final todos = ref.watch(unsortedTodosProvider); // Creates a new sorted list from the combination of the unfiltered // list and the filter type. return [...todos].sort((a, b) { /* ... */ }); }); ``` -------------------------------- ### Using overrideWith with ProviderScope Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/legacy/StateProviderFamily/overrideWith.html Demonstrates how to use the overrideWith method within `ProviderScope.overrides` to replace a provider's implementation. This example shows replacing `myService` with `MyFakeService`. ```APIDOC final myService = Provider((ref) => MyService()); runApp( ProviderScope( overrides: [ myService.overrideWith((ref) { ref.watch('other'); return MyFakeService(); }), ], child: MyApp(), ), ); ``` -------------------------------- ### Building a ConsumerWidget Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/ConsumerWidget/ConsumerWidget.html Demonstrates how to subclass ConsumerWidget and use `ref.watch` to listen to providers within the `build` method. ```APIDOC ## Building a ConsumerWidget ### Description This example shows how to create a custom widget that extends `ConsumerWidget` and subscribes to a `Provider` to display its value. The widget automatically rebuilds when the provider's value changes. ### Usage Example First, define a provider: ```dart final helloWorldProvider = Provider((_) => 'Hello world'); ``` Then, create a `ConsumerWidget` that watches this provider: ```dart class Example extends ConsumerWidget { const Example({Key? key}): super(key: key); @override Widget build(BuildContext context, WidgetRef ref) { final value = ref.watch(helloWorldProvider); return Text(value); // Displays 'Hello world' } } ``` ### Watching Multiple Providers You can watch multiple providers within the `build` method: ```dart @override Widget build(BuildContext context, WidgetRef ref) { final value = ref.watch(someProvider); final another = ref.watch(anotherProvider); return Text(value); // Displays the value from someProvider } ``` ### Important Notes - Do not modify any state or start HTTP requests inside the `build` method. - Use `ref.watch` to subscribe to providers and trigger UI updates. ### See Also - `ConsumerStatefulWidget`: For a stateful widget variant. - `Consumer`: To reduce widget rebuilds without creating a new widget. ``` -------------------------------- ### Using Consumer with Child for Optimization Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/Consumer/child.html This example demonstrates how to use the 'child' parameter of the Consumer widget. The 'child' widget is built once and passed to the builder, improving performance when the child subtree is expensive to build and doesn't depend on the provider's state. ```dart final counterProvider = NotifierProvider(Counter.new); class Counter extends Notifier { @override int build() => 0; void increment() => state++; } class MyHomePage extends ConsumerWidget { MyHomePage({Key? key, required this.title}) : super(key: key); final String title; @override Widget build(BuildContext context, WidgetRef ref) { return Scaffold( appBar: AppBar( title: Text(title) ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text('You have pushed the button this many times:'), Consumer( builder: (BuildContext context, WidgetRef ref, Widget? child) { // This builder will only get called when the counterProvider // is updated. final count = ref.watch(counterProvider); return Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Text('$count'), child!, ], ); }, // The child parameter is most helpful if the child is // expensive to build and does not depend on the value from // the notifier. child: Text('Good job!'), ) ], ), ), floatingActionButton: FloatingActionButton( child: Icon(Icons.plus_one), onPressed: () => ref.read(counterProvider.notifier).increment(), ), ); } } ``` -------------------------------- ### Define a FutureProvider Family for User Data Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/legacy/ChangeNotifierProvider/family-constant.html This example defines a family provider that fetches User data asynchronously based on a userId. It utilizes FutureProvider for asynchronous operations. ```dart final userFamily = FutureProvider.family((ref, userId) async { final userRepository = ref.read(userRepositoryProvider); return await userRepository.fetch(userId); }); ``` -------------------------------- ### Get AsyncError from AsyncValue Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/AsyncValueExtensions/asError.html Use the `asError` property to get an `AsyncError` from an `AsyncValue`. It returns null for `AsyncData` or `AsyncLoading` states. ```dart AsyncError? get asError => map(data: (_) => null, error: (e) => e, loading: (_) => null); ``` -------------------------------- ### Differentiating Provider Access in Riverpod Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/misc/Refreshable-class.html This example shows how to differentiate between directly watching a provider and watching a selected value from a provider. Use `ref.watch(provider)` or `ref.watch(provider.future)` for direct access. ```dart ref.watch(provider); ref.watch(provider.future); ``` ```dart ref.watch(provider.select((value) => value)); ``` -------------------------------- ### overrideWithValue Usage Example Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/FutureProvider/overrideWithValue.html An example demonstrating how to use overrideWithValue to provide a ThemeData to a provider, allowing other providers to access the current theme without a BuildContext. ```APIDOC final themeProvider = Provider((ref) => throw UnimplementedError()); MaterialApp( builder: (context, child) { final theme = Theme.of(context); return ProviderScope( overrides: [ /// We override "themeProvider" with a valid theme instance. /// This allows providers such as "tagThemeProvider" to read the /// current theme, without having a BuildContext. themeProvider.overrideWithValue(theme), ], child: MyApp(), ); }, ); ``` -------------------------------- ### Create a FutureProvider for Configuration Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/FutureProvider/FutureProvider.html Use FutureProvider to expose an object created by reading a JSON file asynchronously. This example demonstrates reading a configuration file using Flutter's asset system. ```dart final configProvider = FutureProvider((ref) async { final content = json.decode( await rootBundle.loadString('assets/configurations.json'), ) as Map; return Configuration.fromJson(content); }); ``` -------------------------------- ### Example of didUpdateProvider being triggered by a mutation Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/ProviderObserver/didUpdateProvider.html This example demonstrates how a mutation can trigger the didUpdateProvider method. When `state++` is called within a mutation, didUpdateProvider is invoked, and the mutation name is recorded. ```dart @riverpod class Example extends _$Example { @override int count() => 0; @mutation int increment() { state++; // This will trigger `didUpdateProvider` and "mutation" will be `#increment` // ... } } ``` -------------------------------- ### state Property Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/legacy/StateController-class.html Gets or sets the current state of the StateController. ```APIDOC ## state ↔ StateT ### Description The current "state" of this StateNotifier. ### Properties - **state** (StateT) - The current state of the controller. This is a getter/setter pair. ``` -------------------------------- ### Provider.family for Repository with Configurations Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/AsyncNotifierProvider/family-constant.html Demonstrates using `Provider.family` where the parameter is another provider, specifically a `FutureProvider` for configurations. This allows a repository to be initialized with dynamic configuration data. ```dart final repositoryProvider = Provider.family>((ref, configurationsProvider) { // Read a provider without knowing what that provider is. final configurations = await ref.read(configurationsProvider.future); return Repository(host: configurations.host); }); ``` -------------------------------- ### ProviderContainer get container Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/experimental_mutation/MutationTarget/container.html The ProviderContainer that is used to run the mutation. ```APIDOC ## container property ProviderContainer get container The ProviderContainer that is used to run the mutation. ### Implementation ```dart ProviderContainer get container; ``` ``` -------------------------------- ### state Property Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/AnyNotifier-class.html Gets or sets the current state exposed by the notifier. ```APIDOC ## state Property ### Description The value currently exposed by this notifier. ### Property - **state** (StateT) - The current state value. This is a getter/setter pair. ``` -------------------------------- ### Override get origin Property Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/misc/Override/origin.html The provider that is overridden. This property is annotated with @visibleForTesting. ```dart @visibleForTesting Override get origin; ``` -------------------------------- ### StateProvider Constructor Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/legacy/StateProvider-class.html Initializes a StateProvider with a create function and optional configuration. ```APIDOC ## StateProvider Constructor ### Description A provider that exposes a value that can be modified from outside. ### Signature StateProvider(ValueT _createFn(Ref ref), {String? name, Iterable? dependencies, bool isAutoDispose = false, Retry? retry}) ``` -------------------------------- ### Get Origin Provider Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/misc/Family/origin.html Returns the provider that is being overridden. This is part of the Family implementation. ```dart @visibleForTesting @override Family get origin => from; ``` -------------------------------- ### create method Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/legacy/StateProvider/create.html The create method is an override that initializes the state using a provided Ref. ```APIDOC ## create method ### Description This method is an override used to create and initialize the state for a StateProvider. It takes a `Ref` object as an argument, which provides access to other providers and services. ### Signature ```dart ValueT create(Ref ref) ``` ### Parameters #### Path Parameters - **ref** (Ref) - Required - An instance of `Ref` used to interact with the Riverpod ecosystem. ### Implementation ```dart @override ValueT create(Ref ref) => _createFn(ref); ``` ``` -------------------------------- ### build() Method Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/AsyncNotifier-class.html Abstract method to initialize the AsyncNotifier. This method should be overridden to provide the initial asynchronous state. ```APIDOC ## build() ### Description Initialize an AsyncNotifier. ### Method `build()` returns `FutureOr` ``` -------------------------------- ### Get Dependency Family Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/misc/ProviderOrFamily/from.html Access the family that this provider or family depends on using the 'from' property. ```dart Family? get from; ``` -------------------------------- ### StateProvider create method implementation Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/legacy/StateProvider/create.html This snippet shows the implementation of the create method for a StateProvider. It delegates the creation logic to a provided function `_createFn`. ```dart @override ValueT create(Ref ref) => _createFn(ref); ``` -------------------------------- ### mutationStart Method Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/ProviderObserver/mutationStart.html This method is invoked when a mutation operation starts. It receives the ProviderObserverContext and the Mutation object. ```APIDOC ## mutationStart Method ### Description A mutation was started. `mutation` is strictly the same as ProviderObserverContext.mutation. It is provided as a convenience, as this life-cycle is guaranteed to have a non-null ProviderObserverContext.mutation. ### Signature ```dart void mutationStart( ProviderObserverContext context, Mutation mutation, ) ``` ### Parameters #### context - **ProviderObserverContext**: The context of the provider observer. #### mutation - **Mutation**: The mutation object that has started. ``` -------------------------------- ### ConsumerStatefulWidget Usage Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/ConsumerStatefulWidget-class.html Demonstrates how to implement a ConsumerStatefulWidget and its associated ConsumerState, showing how to access providers within the State's build method. ```APIDOC ## ConsumerStatefulWidget A StatefulWidget that has a State capable of reading providers. This is used exactly like a StatefulWidget, but with a State that must subclass ConsumerState : ```dart class MyConsumer extends ConsumerStatefulWidget { const MyConsumer({Key? key}): super(key: key); @override ConsumerState createState() => _MyConsumerState(); } class _MyConsumerState extends ConsumerState { @override void initState() { // All State life-cycles can be used super.initState(); } @override Widget build(BuildContext context) { // "ref" is a property of ConsumerState and can be used to read providers ref.watch(someProvider); } } ``` ## Constructors ### ConsumerStatefulWidget ```dart ConsumerStatefulWidget({Key? key}) ``` A StatefulWidget that has a State capable of reading providers. const ``` -------------------------------- ### Get the current state Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/misc/ProviderTransformer/state.html Read the current state of the transformer. When using SyncProviderTransformerMixin, this will rethrow any errors encountered. ```dart AsyncResult get state => _state; ``` -------------------------------- ### build() abstract method Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/AsyncNotifier/build.html Initializes an AsyncNotifier. It's safe to use Ref.watch or Ref.listen within this method. If a dependency changes, build will re-execute without recreating the notifier instance. Errors or failed futures will be caught and emitted as AsyncError. ```APIDOC ## build() abstract method ### Description Initializes an AsyncNotifier. It's safe to use `Ref.watch` or `Ref.listen` inside this method. If a dependency of this AsyncNotifier (when using `Ref.watch`) changes, then `build` will be re-executed. On the other hand, the `AsyncNotifier` will **not** be recreated. Its instance will be preserved between executions of `build`. If this method throws or returns a future that fails, the error will be caught and an `AsyncError` will be emitted. ### Implementation ```dart @visibleForOverriding FutureOr build(); ``` ``` -------------------------------- ### Override get origin Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/misc/Override/origin.html The `origin` property returns the provider that is being overridden. This is useful for understanding the context of an override. ```APIDOC ## Override get origin ### Description The provider that is overridden. ### Implementation ```dart @visibleForTesting Override get origin; ``` ``` -------------------------------- ### build() Method Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/StreamNotifier-class.html Abstract method to initialize the stream for the notifier. ```APIDOC ## build() ### Description Initializes an AsyncNotifier by returning a Stream. This method must be implemented by subclasses to provide the stream of values. ### Method Signature `Stream build()` ### Returns A `Stream` that emits values of type `ValueT`. ``` -------------------------------- ### Get State Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/legacy/StateNotifier/state.html Retrieves the current state of the StateNotifier. Accessing this property is synchronous and will call listeners if the state changes. ```APIDOC ## Get State ### Description Retrieves the current state of the StateNotifier. Updating this variable will synchronously call all the listeners. Notifying the listeners is O(N) with N the number of listeners. Updating the state will throw if at least one listener throws. ### Method `get state` ### Return Value - **T** - The current state of the StateNotifier. ``` -------------------------------- ### StorageOptions Constructor Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/experimental_persist/StorageOptions-class.html Initializes StorageOptions with optional destroyKey and cacheTime. ```APIDOC ## StorageOptions Constructor ### Description Options to enable a Storage to persist state. ### Signature ```dart StorageOptions({String? destroyKey, StorageCacheTime cacheTime = const StorageCacheTime(Duration(days: 2))}) ``` ### Parameters #### Named Parameters - **destroyKey** (String?): A key to forcibly destroy the associated state. - **cacheTime** (StorageCacheTime): The time before the data expires. Defaults to `const StorageCacheTime(Duration(days: 2))`. ``` -------------------------------- ### Implementing the create method Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/legacy/StateNotifierProvider/create.html This snippet shows the typical implementation of the `create` method for a `StateNotifierProvider`. It delegates the creation logic to a private `_create` function, passing the `Ref` object. ```dart @override NotifierT create(Ref ref) => _create(ref); ``` -------------------------------- ### Empty implementation of didUpdateProvider Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/ProviderObserver/didUpdateProvider.html A basic implementation of the didUpdateProvider method, often used as a starting point for custom provider observers. ```dart void didUpdateProvider( ProviderObserverContext context, Object? previousValue, Object? newValue, ) {} ``` -------------------------------- ### $view Method Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/legacy/ChangeNotifierProvider/%24view.html Creates a ChangeNotifierProvider. This method is an override that takes a required `create` function to instantiate the Notifier. ```APIDOC ## $view Method ### Description Creates a `ChangeNotifierProvider` with a given `create` function. ### Method Signature ```dart ChangeNotifierProvider $view({ required Create create, }) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **create** (Create) - Required - A function that creates an instance of `NotifierT`. ``` -------------------------------- ### Using notifyListeners in a Notifier Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/Ref/notifyListeners.html This example demonstrates how to use ref.notifyListeners() within a Notifier to update dependents when the state of a mutable list changes. ```dart class TodoList extends Notifier> { @override List> build() => []; void addTodo(Todo todo) { state.add(todo); ref.notifyListeners(); } } ``` -------------------------------- ### StateProvider Constructor Implementation Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/legacy/StateProvider/StateProvider.html Shows the internal implementation of the StateProvider constructor, including its parameters and superclass initialization. ```dart StateProvider( this._createFn, { super.name, super.dependencies, super.isAutoDispose = false, super.retry, }, ) : super( $allTransitiveDependencies: computeAllTransitiveDependencies( dependencies, ), from: null, argument: null, ); ``` -------------------------------- ### StateProvider Methods Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/legacy/StateProvider-class.html Methods available for StateProvider instances. ```APIDOC ## StateProvider Methods ### create @nodoc ### noSuchMethod Invoked when a nonexistent method or property is accessed. ### overrideWith Override the provider with a new initialization function. ### select Partially listen to a provider. ### toString A string representation of this object. ``` -------------------------------- ### Get State Property Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/legacy/StateController/state.html Overrides the getter for the state property to return the current state. Updating this property synchronously calls listeners. ```dart @override StateT get state => super.state; ``` -------------------------------- ### get Method Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/experimental_mutation/MutationTransaction/get.html Reads the current state of a listenable and maintains a subscription to it until the transaction completes. Updates to the listenable during the transaction are ignored. ```APIDOC ## get Method ### Description Reads the current state of a listenable and maintains a subscription to it until the transaction completes. Updates to the listenable during the transaction are ignored. ### Method Signature StateT get( 1. ProviderListenable listenable ) ``` -------------------------------- ### ProviderObserver mutationStart Implementation Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/ProviderObserver/mutationStart.html This is the basic implementation signature for the mutationStart method. It is called when a mutation starts and receives the context and the mutation object. ```dart void mutationStart( ProviderObserverContext context, Mutation mutation, ) {} ``` -------------------------------- ### Implementing a Counter with Notifier Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/Notifier-class.html Demonstrates how to create a simple counter using the Notifier class. The initial state is defined in the build method, and state modifications are handled by dedicated methods. ```dart final counterProvider = NotifierProvider(Counter.new); class Counter extends Notifier { @override int build() { // Inside "build", we return the initial state of the counter. return 0; } void increment() { state++; } } ``` -------------------------------- ### Using ConsumerStatefulWidget and ConsumerState Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/ConsumerState-class.html Demonstrates how to create a ConsumerStatefulWidget and its corresponding ConsumerState. The 'ref' property is available within the ConsumerState to interact with providers. ```dart class MyConsumer extends ConsumerStatefulWidget { const MyConsumer({Key? key}): super(key: key); @override ConsumerState createState() => _MyConsumerState(); } class _MyConsumerState extends ConsumerState { @override void initState() { // All State life-cycles can be used super.initState(); } @override Widget build(BuildContext context) { // "ref" is a property of ConsumerState and can be used to read providers ref.watch(someProvider); } } ``` -------------------------------- ### WidgetRef.listen Method Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/WidgetRef/listen.html Listens to a provider and invokes a callback when the provider's state changes. This method should be used at the root of the `build` method or within builders. ```APIDOC ## listen ### Description Listens to a provider and calls `listener` whenever its value changes, without having to take care of removing the listener. The `listen` method should exclusively be used at the root of the `build` method or within builders. ### Method Signature ```dart void listen( ProviderListenable provider, void Function(StateT? previous, StateT next) listener, { void Function(Object error, StackTrace stackTrace)? onError, bool weak = false } ) ``` ### Parameters - **provider** (`ProviderListenable`): The provider to listen to. - **listener** (`void Function(StateT? previous, StateT next)`): A callback function that is invoked when the provider's state changes. It receives the previous and the next state. - **onError** (`void Function(Object error, StackTrace stackTrace)`) (Optional): A callback function to handle errors that occur during provider state updates. - **weak** (`bool`) (Optional, defaults to `false`): If true, the listener will be a weak reference, allowing the provider to be disposed if no other listeners are active. ``` -------------------------------- ### AsyncNotifierProvider Implementation Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/AsyncNotifierProvider/AsyncNotifierProvider.html Shows the implementation of the AsyncNotifierProvider constructor, extending the base class and computing transitive dependencies. ```dart AsyncNotifierProvider( this._createNotifier, { super.name, super.dependencies, super.isAutoDispose = false, super.retry, }) : super( $allTransitiveDependencies: computeAllTransitiveDependencies( dependencies, ), from: null, argument: null, ); ``` -------------------------------- ### Overriding a provider with overrideWith Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/AsyncNotifierProvider/overrideWith.html Demonstrates how to use `overrideWith` within `ProviderScope` to replace a provider's implementation. This example replaces `myService` with a `MyFakeService`. ```dart final myService = Provider((ref) => MyService()); runApp( ProviderScope( overrides: [ // Replace the implementation of the provider with a different one myService.overrideWith((ref) { ref.watch('other'); return MyFakeService(); }) ], child: MyApp(), ), ); ``` -------------------------------- ### Correct Usage of WidgetRef.listen Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/WidgetRef/listen.html Use `ref.listen` at the root of the `build` method. This ensures proper listener management and avoids unexpected behavior. ```dart class Example extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { // Correct, we are inside the build method and at its root. ref.listen(counterProvider, (prev, next) {}); } } ``` -------------------------------- ### Get mounted status Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/legacy/StateNotifier/mounted.html Use this getter to check if the StateNotifier has been disposed. It returns `true` if the notifier is still active and `false` if `dispose` has been called. ```dart bool get mounted => _mounted; ``` -------------------------------- ### Incorrect Usage: Outside build method Source: https://pub.dev/documentation/flutter_riverpod/3.3.0/flutter_riverpod/WidgetRef/listen.html Demonstrates incorrect usage of `ref.listen` outside of the `build` method, such as in `initState`. ```dart class ExampleState extends ConsumerState { @override void initState() { super.initState(); // Incorrect: ref.listen cannot be used here. ref.listen(userProvider, (prev, next) { print('User updated: $next'); }); } @override Widget build(BuildContext context) { // Correct usage would be here: // ref.listen(userProvider, (prev, next) { ... }); return Container(); } } ```