### Refreshable provider usage examples Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/misc/Refreshable-class.html Examples showing provider expressions that are compatible with ref.refresh versus those that are not. ```dart ref.watch(provider); ref.watch(provider.future); ``` ```dart ref.watch(provider.select((value) => value)); ``` -------------------------------- ### Define a FutureProvider for configuration Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/FutureProvider/FutureProvider.html Example of using FutureProvider to load and parse a JSON configuration file asynchronously. ```dart final configProvider = FutureProvider((ref) async { final content = json.decode( await rootBundle.loadString('assets/configurations.json'), ) as Map; return Configuration.fromJson(content); }); ``` -------------------------------- ### ConsumerState Usage Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/ConsumerState-class.html Example of how to implement a ConsumerStatefulWidget and its corresponding ConsumerState to access providers via the ref property. ```APIDOC ## ConsumerState ### Description ConsumerState is the base class for the state of a ConsumerStatefulWidget. It functions identically to a standard Flutter State class but includes a `ref` property for provider interaction. ### Properties - **ref** (WidgetRef) - An object that allows widgets to interact with providers. ### Usage Example ```dart class MyConsumer extends ConsumerStatefulWidget { const MyConsumer({Key? key}): super(key: key); @override ConsumerState createState() => _MyConsumerState(); } class _MyConsumerState extends ConsumerState { @override Widget build(BuildContext context) { // Use "ref" to read providers final value = ref.watch(someProvider); return Container(); } } ``` ``` -------------------------------- ### void mutationStart(ProviderObserverContext context, Mutation mutation) Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/ProviderObserver/mutationStart.html This method is called when a mutation starts. It provides the ProviderObserverContext and the specific Mutation object being executed. ```APIDOC ## void mutationStart(ProviderObserverContext context, Mutation mutation) ### Description A lifecycle method triggered when a mutation starts. The mutation parameter is provided as a convenience and is guaranteed to be the same as ProviderObserverContext.mutation. ### Parameters - **context** (ProviderObserverContext) - The context associated with the observer. - **mutation** (Mutation) - The mutation instance that has started. ``` -------------------------------- ### Implement a custom ProviderListenable with SyncProviderTransformerMixin Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/misc/SyncProviderTransformerMixin-mixin.html This example demonstrates creating a 'Where' class using the mixin to filter provider updates, along with an extension to apply it to any ProviderListenable. ```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); } ``` -------------------------------- ### Incorrect usage of family provider Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/AsyncNotifierProvider/family-constant.html Example of invalid syntax when attempting to watch a family provider without passing a parameter. ```dart Widget build(BuildContext context, WidgetRef ref) { // Error – messagesFamily is not a provider final response = ref.watch(messagesFamily); } ``` -------------------------------- ### Future run(MutationTarget target, Future cb(MutationTransaction transaction)) Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/experimental_mutation/Mutation/run.html Starts a mutation and sets its state based on the result of the provided callback. It manages provider lifecycles and subscription cleanup during the transaction. ```APIDOC ## run ### Description Starts a mutation and sets its state based on the result of the callback. It transitions the mutation state to MutationPending, executes the callback, and updates the state to MutationSuccess or MutationError based on the outcome. ### Signature `Future run(MutationTarget target, Future Function(MutationTransaction transaction) cb)` ### Parameters - **target** (MutationTarget) - The target of the mutation. - **cb** (Future Function(MutationTransaction)) - A callback function that receives a MutationTransaction to interact with providers. ``` -------------------------------- ### Get state implementation Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/AsyncNotifier/state.html The getter for the current AsyncValue state. ```dart @visibleForTesting @protected @override AsyncValue get state; ``` -------------------------------- ### Using the Consumer builder Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/Consumer/builder.html Demonstrates watching multiple providers within the Consumer builder function. ```dart Consumer( builder: (context, ref, child) { final value = ref.watch(someProvider); final another = ref.watch(anotherProvider); ... }, ); ``` -------------------------------- ### Define a Riverpod Provider Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/Consumer/Consumer.html An example of a provider definition using the @riverpod annotation. ```dart @riverpod Future fetchUser(Ref ref) async { // ... } ``` -------------------------------- ### build() Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/AsyncNotifier-class.html Initializes the AsyncNotifier. This method must be implemented to define the asynchronous logic for the initial state. ```APIDOC ## build() ### Description Initializes the AsyncNotifier. This method is called to compute the initial state of the notifier asynchronously. ### Signature `FutureOr build()` ``` -------------------------------- ### build(BuildContext context, WidgetRef ref) Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/ConsumerWidget-class.html The build method is where you define the widget's UI and watch providers using the provided WidgetRef. ```APIDOC ## Widget build(BuildContext context, WidgetRef ref) ### Description Describes the part of the user interface represented by this widget. Use the `ref.watch` method to listen to providers and trigger rebuilds when their values change. ### Parameters - **context** (BuildContext) - The build context in which the widget is built. - **ref** (WidgetRef) - The reference used to interact with providers (e.g., `ref.watch`). ### Returns - **Widget** - The UI representation of the widget. ``` -------------------------------- ### bool get closed Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/ProviderSubscription/closed.html Returns true if the subscription is closed, false otherwise. ```APIDOC ## bool get closed ### Description Returns a boolean value indicating whether the subscription is currently closed. ### Signature `bool get closed` ``` -------------------------------- ### ValueT build() Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/Notifier/build.html Initializes the Notifier. This method is intended to be overridden by the user to define the initial state and dependencies of the provider. ```APIDOC ## ValueT build() ### Description Initializes a Notifier. It is safe to use Ref.watch or Ref.listen inside this method. If a dependency of this Notifier (when using Ref.watch) changes, then build will be re-executed, but the Notifier instance will be preserved. ### Signature `ValueT build()` ### Behavior - If this method throws, reading this provider will rethrow the error. - The Notifier instance is preserved between executions of build. ### Implementation ```dart @visibleForOverriding ValueT build(); ``` ``` -------------------------------- ### Pull-to-refresh implementation Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/WidgetRef/refresh.html Example of using ref.refresh within a RefreshIndicator to trigger a FutureProvider update. ```dart final productsProvider = FutureProvider((ref) async { final response = await httpClient.get('https://host.com/products'); return Products.fromJson(response.data); }); class Example extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final Products products = ref.watch(productsProvider); return RefreshIndicator( onRefresh: () => ref.refresh(productsProvider.future), child: ListView( children: [ for (final product in products.items) ProductItem(product: product), ], ), ); } } ``` -------------------------------- ### Override hashCode implementation Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/experimental_mutation/MutationIdle/hashCode.html Example of overriding the hashCode property to return a constant value. ```dart @override int get hashCode => 0; ``` -------------------------------- ### bool get isPaused Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/ProviderSubscription/isPaused.html Returns a boolean value indicating if the subscription is currently paused. ```APIDOC ## bool get isPaused ### Description Whether the subscription is paused. Upon resuming the subscription, if any event was sent while paused, the last event will be sent to the listener. ### Signature `bool get isPaused` ``` -------------------------------- ### Using multiple family parameters Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/AsyncNotifierProvider/family-constant.html Demonstrates watching the same family provider with different parameters simultaneously. ```dart @override Widget build(BuildContext context, WidgetRef ref) { final frenchTitle = ref.watch(titleFamily(const Locale('fr'))); final englishTitle = ref.watch(titleFamily(const Locale('en'))); return Text('fr: $frenchTitle en: $englishTitle'); } ``` -------------------------------- ### bool get isPending Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/experimental_mutation/MutationState/isPending.html A getter property that returns true if the mutation is currently pending. ```APIDOC ## bool get isPending ### Description Returns a boolean indicating whether the mutation is currently pending. This is equivalent to checking if the mutation state is `MutationPending`. ### Signature `bool get isPending` ### Returns - **bool** - True if the mutation is pending, false otherwise. ``` -------------------------------- ### Using notifyListeners in a Notifier Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/Ref/notifyListeners.html Example of calling notifyListeners after modifying a mutable list state within a Notifier. ```dart class TodoList extends Notifier> { @override List> build() => []; void addTodo(Todo todo) { state.add(todo); ref.notifyListeners(); } } ``` -------------------------------- ### Storage constructor Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/experimental_persist/Storage/Storage.html Initializes a new instance of the Storage interface to enable database interaction for Riverpod persistence. ```APIDOC ## Storage constructor ### Description Creates an interface to enable Riverpod to interact with a database. This is used in conjunction with NotifierPersistX.persist to enable persistence for a notifier. ### Signature Storage() ``` -------------------------------- ### Get state property Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/misc/ProviderTransformer/state.html Retrieves the currently exposed state of the transformer, rethrowing errors when using SyncProviderTransformerMixin. ```dart AsyncResult get state => _state; ``` -------------------------------- ### overrideWith(StateT create(Ref ref, ArgT arg)) Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/misc/ProviderFamily-class.html Overrides the provider's initialization function with a new implementation. ```APIDOC ## overrideWith(StateT create(Ref ref, ArgT arg)) ### Description Overrides the provider with a new initialization function. This is typically used for testing or to provide different implementations for specific arguments. ### Signature `Override overrideWith(StateT create(Ref ref, ArgT arg))` ### Parameters - **create** (Function) - A function that takes a `Ref` and the `ArgT` argument to return the state. ``` -------------------------------- ### get(ProviderListenable listenable) Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/experimental_mutation/MutationTransaction-class.html Reads the current state of a listenable and maintains a subscription to it until the transaction completes. ```APIDOC ## get(ProviderListenable listenable) ### Description Reads the current state of a listenable and maintains a subscription to it until the transaction completes. ### Parameters - **listenable** (ProviderListenable) - Required - The provider or listenable to read and subscribe to. ### Returns - **StateT** - The current state of the provided listenable. ``` -------------------------------- ### Basic usage of ref.refresh Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/WidgetRef/refresh.html Demonstrates the direct usage of the refresh method. ```dart final newValue = ref.refresh(provider); ``` -------------------------------- ### Implement mutationStart in ProviderObserver Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/ProviderObserver/mutationStart.html Defines the mutationStart method signature within a ProviderObserver class. ```dart void mutationStart( ProviderObserverContext context, Mutation mutation, ) {} ``` -------------------------------- ### bool isFirstBuild Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/Ref/isFirstBuild.html A boolean property that returns true if the provider is being initialized for the first time. ```APIDOC ## bool isFirstBuild ### Description Returns a boolean indicating whether the provider is currently initializing for the first time. When using `Provider.autoDispose`, this flag resets to `true` if the provider's state is destroyed and subsequently recreated. ### Signature `final bool isFirstBuild;` ``` -------------------------------- ### num? get progress Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/AsyncValueExtensions/progress.html Retrieves the current progress of an asynchronous operation. The value is null by default and should be between 0 and 1 when set. ```APIDOC ## num? get progress ### Description The current progress of the asynchronous operation. This value must be between 0 and 1. By default, the progress will always be null. ### Usage ```dart state = AsyncLoading(progress: 0); await something(); ref.state = AsyncLoading(progress: 1); ``` ``` -------------------------------- ### bool get isRefreshing Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/AsyncValueExtensions/isRefreshing.html Returns true if the provider is currently being refreshed via Ref.invalidate or Ref.refresh, but not due to a dependency change. ```APIDOC ## bool get isRefreshing ### Description Returns a boolean indicating if the associated provider was forced to recompute even though none of its dependencies have changed, after at least one value or error was emitted. This is typically true when using `Ref.invalidate` or `Ref.refresh`. ### Usage If a provider rebuilds because a dependency changed (via `Ref.watch`), `isRefreshing` will be `false` and `isReloading` will be `true`. ``` -------------------------------- ### select Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/Provider-class.html Partially listen to a provider. ```APIDOC ### Method select(OutT selector(InT value)) → ProviderListenable ### Description Partially listen to a provider. Available on ProviderListenable. ``` -------------------------------- ### Widget build(BuildContext context, WidgetRef ref) Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/Consumer/build.html The build method is called by the framework to construct the widget's UI. It receives a BuildContext and a WidgetRef, which allows the widget to interact with Riverpod providers. ```APIDOC ## Widget build(BuildContext context, WidgetRef ref) ### Description Describes the part of the user interface represented by this widget. The framework calls this method when the widget is inserted into the tree or when its dependencies change. ### Parameters - **context** (BuildContext) - The location in the tree at which this widget is being built. - **ref** (WidgetRef) - A reference used to interact with Riverpod providers. ### Returns - **Widget** - A newly created constellation of widgets representing the UI. ``` -------------------------------- ### bool get hasError Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/AsyncValueExtensions/hasError.html A getter that returns true if the AsyncValue contains an error. Note that this can be true simultaneously with hasValue or isLoading. ```APIDOC ## bool get hasError ### Description Returns a boolean indicating whether the current AsyncValue instance contains an error. This property is true if the error field is not null. ### Usage ```dart if (asyncValue.hasError) { // Handle the error state } ``` ### Notes - Even if hasError is true, it is still possible for hasValue or isLoading to also be true. ``` -------------------------------- ### Override hashCode implementation Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/AsyncValue/hashCode.html Example of overriding the hashCode property to include internal state variables, ensuring consistency with equality checks. ```dart @override int get hashCode => Object.hash(runtimeType, _loading, valueFilled, _errorFilled); ``` -------------------------------- ### Correct usage of ref.listen Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/WidgetRef/listen.html Use listen at the root of the build method to observe provider changes. ```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) {}); } } ``` -------------------------------- ### build() Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/StreamNotifier-class.html Initializes the StreamNotifier by returning a Stream of values. ```APIDOC ## Stream build() ### Description Initializes the AsyncNotifier. This method must be implemented to return the Stream that the notifier will expose. ### Returns - **Stream** - The stream of values to be exposed by the notifier. ``` -------------------------------- ### bool get isReloading Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/AsyncValueExtensions/isReloading.html Returns true if the provider is recomputing due to a dependency change (Ref.watch) after an initial value or error has been emitted. ```APIDOC ## bool get isReloading ### Description Returns a boolean indicating if the provider is currently recomputing because one of its dependencies changed (via Ref.watch). This property is true only if the provider has already emitted at least one value or error. ### Usage Use this property to distinguish between a provider reloading due to dependency changes versus a manual refresh or invalidation. ### See Also - isRefreshing: Used for manual provider rebuilds via Ref.invalidate or Ref.refresh. ``` -------------------------------- ### listen Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/ProviderContainer-class.html Subscribes to a provider and executes a listener function when its value changes. ```APIDOC ## listen(provider, listener, {fireImmediately, weak, onError}) ### Description Listen to a provider and call `listener` whenever its value changes. ### Parameters - **provider** (ProviderListenable) - Required - The provider to listen to. - **listener** (Function) - Required - Callback function receiving previous and next states. - **fireImmediately** (bool) - Optional - Whether to trigger the listener immediately. - **weak** (bool) - Optional - Whether the subscription is weak. ``` -------------------------------- ### bool get isLoading Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/AsyncValueExtensions/isLoading.html Returns true if the AsyncValue is currently performing an asynchronous operation. Note that this can be true simultaneously with hasValue or hasError. ```APIDOC ## bool get isLoading ### Description Returns a boolean indicating whether a new value is currently being asynchronously loaded. This property remains true during loading states, regardless of whether the instance already holds a previous value or an error. ### Signature `bool get isLoading` ### Returns - **bool**: True if the operation is currently loading, false otherwise. ``` -------------------------------- ### get method Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/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. Note that updates to the listenable during the transaction are ignored. ### Signature `StateT get(ProviderListenable listenable)` ### Parameters - **listenable** (ProviderListenable) - Required - The provider listenable to read and subscribe to. ### Returns - **StateT** - The current state of the listenable. ``` -------------------------------- ### Using selectAsync with FutureProvider Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/AsyncNotifierProvider/selectAsync.html Demonstrates how to use selectAsync to watch a specific property of an asynchronous configuration provider, ensuring the dependent provider only rebuilds when that property changes. ```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'); }); ``` -------------------------------- ### Implementation of get Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/experimental_mutation/MutationTransaction/get.html Reads the current state of a listenable and maintains a subscription until the transaction completes. Updates to the listenable during the transaction are ignored. ```dart StateT get(ProviderListenable listenable) { assert( !_closed, 'Cannot get a listenable after the transaction has been closed', ); final sub = _container.listen( listenable, (previous, next) {}, onError: (error, stackTrace) {}, ); _subscriptions.add(sub); return sub.readSafe().valueOrProviderException; } ``` -------------------------------- ### Mutation.run Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/experimental_mutation/Mutation-class.html Executes the mutation logic. ```APIDOC ## Mutation.run ### Description Executes the mutation. Note that mutations do not restrict concurrent calls; if run is called while a previous call is pending, the state resets to MutationPending and the previous result is ignored. ### Usage `mutation.run(ref, (tsx) async { /* logic */ })` ``` -------------------------------- ### int get hashCode Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/Provider/hashCode.html Returns the hash code for the object, which is calculated based on the object's state to ensure consistency with operator ==. ```APIDOC ## int get hashCode ### Description The hash code is a single integer representing the state of the object that affects operator == comparisons. It must be overridden whenever operator == is overridden to ensure compatibility with hash-based collections like Set and Map. ### Implementation ```dart @override int get hashCode { if (from == null) return super.hashCode; return from.hashCode ^ argument.hashCode; } ``` ``` -------------------------------- ### StorageOptions Implementation Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/experimental_persist/StorageOptions/StorageOptions.html The default constructor for StorageOptions, defining the destroyKey and cacheTime parameters. ```dart const StorageOptions({ this.destroyKey, this.cacheTime = const StorageCacheTime(Duration(days: 2)), }); ``` -------------------------------- ### bool get retrying Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/AsyncValueExtensions/retrying.html Returns true if an error is currently being retried, even if the value is not currently loading (e.g., waiting for a retry delay). ```APIDOC ## bool get retrying ### Description Returns a boolean indicating if an error emitted by the AsyncValue is currently being retried. This can be true while isLoading is false if a retry is scheduled but the delay has not yet elapsed. ### Signature `bool get retrying` ### Returns - **bool** - True if the error is being retried, false otherwise. ``` -------------------------------- ### resume() Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/ProviderSubscription-class.html Resumes the subscription. ```APIDOC ### void resume() Resumes the subscription. ``` -------------------------------- ### bool get hasValue Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/AsyncValueExtensions/hasValue.html Returns true if the AsyncValue contains a value. Note that this can be true even if the state is currently loading or contains an error. ```APIDOC ## bool get hasValue ### Description Returns a boolean indicating whether a value is currently set in the AsyncValue. This property remains true even if the instance is in a loading state or has an error state. ### Signature `bool get hasValue` ### Returns - **bool**: True if the value is set, false otherwise. ``` -------------------------------- ### ConsumerState() Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/ConsumerState/ConsumerState.html Initializes a new instance of ConsumerState for a given ConsumerStatefulWidget. ```APIDOC ## ConsumerState() ### Description Creates a state object for a ConsumerStatefulWidget. This allows the widget to access Riverpod providers via the `ref` property. ### Signature `ConsumerState()` ``` -------------------------------- ### Sorting a todo-list with watch Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/Ref/watch.html Demonstrates using watch to combine multiple providers into a single derived state that updates automatically. ```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) { ... }); }); ``` -------------------------------- ### bool get mounted Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/Ref/mounted.html A getter that returns a boolean indicating whether the Ref is still active. If false, the provider is disposed and its methods should no longer be used. ```APIDOC ## bool get mounted ### Description Returns a boolean indicating whether the current Ref is still active. When false, the provider has been disposed, and further operations should be halted to avoid race conditions. ### Usage ```dart final myProvider = FutureProvider((ref) async { await someAsyncOperation(); if (!ref.mounted) return; // Stop execution if provider is disposed // Continue logic... }); ``` ``` -------------------------------- ### Default implementation of runBuild Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/AsyncNotifier/runBuild.html The standard implementation of runBuild which handles the creation of the notifier element. ```dart @mustCallSuper @override void runBuild() { requireElement().handleCreate(ref, build); } ``` -------------------------------- ### AsyncValue get state Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/AsyncNotifier/state.html Retrieves the current value exposed by the notifier. Reading this property may trigger the build method if the provider is out of date. ```APIDOC ## AsyncValue get state ### Description Returns the current value exposed by the notifier. If the provider is out of date, accessing this property triggers the re-execution of the build method. ### Signature `AsyncValue get state` ``` -------------------------------- ### StorageOptions constructor Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/experimental_persist/StorageOptions-class.html Creates a new instance of StorageOptions to configure how state is persisted. ```APIDOC ## StorageOptions({String? destroyKey, StorageCacheTime cacheTime = const StorageCacheTime(Duration(days: 2))}) ### Description Initializes the options used to enable a Storage to persist state. These options are passed to NotifierPersistX.persist. ### Parameters - **destroyKey** (String?) - Optional - A key to forcibly destroy the associated state. - **cacheTime** (StorageCacheTime) - Optional - The time before the data expires. Defaults to 2 days. ``` -------------------------------- ### listen method Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/ProviderContainer/listen.html Subscribes to a provider and executes a callback whenever the provider's value changes. Returns a ProviderSubscription object to manage or cancel the subscription. ```APIDOC ## listen ### Description Listens to a provider and calls the provided listener function whenever its value changes. The subscription can be cancelled using the returned ProviderSubscription object. ### Signature ProviderSubscription listen( ProviderListenable provider, void listener(StateT? previous, StateT next), {bool fireImmediately = false, bool weak = false, void onError(Object error, StackTrace stackTrace)?} ) ### Parameters - **provider** (ProviderListenable) - The provider to listen to. - **listener** (Function(StateT? previous, StateT next)) - Callback invoked when the provider state changes. - **fireImmediately** (bool) - Optional. If true, calls the listener immediately with the current value. Defaults to false. - **weak** (bool) - Optional. If true, the listener does not force the provider to initialize or stay alive. Defaults to false. - **onError** (Function(Object error, StackTrace stackTrace)) - Optional. Callback for uncaught errors in the provider. ### Returns - **ProviderSubscription** - An object used to cancel the subscription. ``` -------------------------------- ### String toString() Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/ProviderObserverContext/toString.html Returns a string representation of the ProviderObserverContext, including the provider, container, and optional mutation details. ```APIDOC ## String toString() ### Description Returns a string representation of the ProviderObserverContext object. This is primarily used for debugging and logging to inspect the state of the context. ### Signature `String toString()` ### Returns - **String**: A formatted string containing the provider, container, and mutation information. ``` -------------------------------- ### bool get isPaused Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/Ref/isPaused.html Returns a boolean indicating if the Ref is currently paused. A provider is considered paused when all of its listeners are removed or inactive, such as when a widget is not visible due to TickerMode. ```APIDOC ## bool get isPaused ### Description Returns whether this Ref is currently paused. A provider is paused when all of its listeners are removed or temporarily inactive. The state remains in memory but stops notifying listeners until it resumes. ### Signature `bool get isPaused` ### Returns - **bool**: True if the provider is paused, false otherwise. ``` -------------------------------- ### Using Provider.family with Locale Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/AsyncNotifierProvider/family-constant.html Demonstrates creating a provider that depends on a Locale and watching it within a widget. ```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'; } }); // ... @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); } ``` -------------------------------- ### bool get weak Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/ProviderSubscription/weak.html Returns a boolean indicating if the subscription maintains the provider state. If false, the provider may be disposed despite an active subscription if it is configured for auto-dispose. ```APIDOC ## bool get weak ### Description Whether the subscription maintains the provider state. If false and ProviderBase.isAutoDispose is true, the provider may still be disposed even if this subscription is active. ### Signature `bool get weak` ``` -------------------------------- ### bool get isFromCache Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/AsyncValueExtensions/isFromCache.html A getter that returns true if the AsyncValue was obtained using Riverpod's offline-persistence feature. When this is true, the isLoading state is typically also true. ```APIDOC ## bool get isFromCache ### Description Returns a boolean indicating whether the current value was retrieved from the offline-persistence cache. When this property is true, the associated AsyncValue is also expected to be in a loading state. ### Signature `bool get isFromCache` ### Returns - **bool**: True if the value is from cache, false otherwise. ``` -------------------------------- ### StreamProvider(Create> _create, {String? name, Iterable? dependencies, bool isAutoDispose = false, Retry? retry}) Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/StreamProvider-class.html Constructor to create a new StreamProvider instance. ```APIDOC ## StreamProvider Constructor ### Description Creates a stream and exposes its latest event. This provider is used to handle asynchronous streams in a reactive way. ### Parameters - **_create** (Create>) - Required - The function that creates the stream. - **name** (String?) - Optional - A custom label for the provider. - **dependencies** (Iterable?) - Optional - The list of providers that this provider potentially depends on. - **isAutoDispose** (bool) - Optional - Whether the state should be disposed automatically when no longer listened to. - **retry** (Retry?) - Optional - The retry strategy to use when a provider fails. ``` -------------------------------- ### NotifierProvider constructor Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/NotifierProvider/NotifierProvider.html Creates a new NotifierProvider instance to manage state using a synchronous Notifier. ```APIDOC ## NotifierProvider constructor ### Description Creates a provider that exposes a synchronous Notifier. It is used for managing state that requires mutability. ### Signature NotifierProvider, ValueT>( NotifierT _createNotifier(), { String? name, Iterable? dependencies, bool isAutoDispose = false, Retry? retry, }) ``` -------------------------------- ### Define a basic provider Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/Provider/Provider.html Creates a simple provider that returns a static string value. ```dart final cityProvider = Provider((ref) => 'London'); ``` -------------------------------- ### Implementation of the listen method Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/Ref/listen.html The internal implementation of the listen method within Riverpod, showing the signature and delegation to the element. ```dart ProviderSubscription listen( ProviderListenable provider, void Function(StateT? previous, StateT next) listener, { void Function(Object error, StackTrace stackTrace)? onError, bool weak = false, bool fireImmediately = false, }) { _throwIfInvalidUsage(); return _element.listen( provider, listener, weak: weak, onError: onError, fireImmediately: fireImmediately, ); } ``` -------------------------------- ### FutureOr build() Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/AsyncNotifier/build.html Initializes the AsyncNotifier. This method is intended to be overridden to define the initial state or logic for the notifier. It is safe to use Ref.watch or Ref.listen within this method, and it will re-execute if dependencies change. ```APIDOC ## FutureOr build() ### Description Initializes an AsyncNotifier. It is 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, but the AsyncNotifier instance will be preserved. ### Signature `FutureOr build()` ### Behavior - If this method throws or returns a future that fails, the error will be caught and an AsyncError will be emitted. - The method is marked with @visibleForOverriding. ``` -------------------------------- ### Initialize Storage Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/experimental_persist/Storage/Storage.html The constructor initializes the storage instance and triggers the cleanup of out-of-date data. ```dart Storage() { deleteOutOfDate(); } ``` -------------------------------- ### Conceptual implementation of watch Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/Ref/watch.html A simplified conceptual representation showing how watch combines listen and invalidateSelf. ```dart T watch(ProviderListenable provider) { final sub = listen(provider, (previous, next) { invalidateSelf(asReload: true); }); return sub.read(); } ``` -------------------------------- ### run abstract method signature Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/experimental_mutation/Mutation/run.html The method signature for initiating a mutation with a target and a callback function. ```dart Future run( MutationTarget target, Future Function(MutationTransaction transaction) cb, ); ``` -------------------------------- ### Combine multiple providers in a class Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/Provider/Provider.html Demonstrates creating an object that depends on multiple providers by watching them within the provider definition. ```dart final cityProvider = Provider((ref) => 'London'); final countryProvider = Provider((ref) => 'England'); final weatherProvider = Provider((ref) { final city = ref.watch(cityProvider); final country = ref.watch(countryProvider); return Location(city: city, country: country); }); class Location { Location({required this.city, required this.country}); final String city; final String country; String get label => '$city ($country)'; } ``` -------------------------------- ### Widget build(BuildContext context, WidgetRef ref) Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/ConsumerWidget/build.html Describes the part of the user interface represented by this widget. The framework calls this method when this widget is inserted into the tree or when dependencies change. ```APIDOC ## Widget build(BuildContext context, WidgetRef ref) ### Description Describes the part of the user interface represented by this widget. The framework calls this method when this widget is inserted into the tree in a given BuildContext and when the dependencies of this widget change. ### Parameters - **context** (BuildContext) - The location in the tree at which this widget is being built. - **ref** (WidgetRef) - A reference used to interact with Riverpod providers. ### Returns - **Widget** - A newly created constellation of widgets that are configured with information from this widget's constructor and from the given BuildContext. ### Implementation ```dart Widget build(BuildContext context, WidgetRef ref); ``` ``` -------------------------------- ### ProviderContainer.listen Implementation Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/ProviderContainer/listen.html The internal implementation of the listen method, including validation for weak and fireImmediately parameters. ```dart ProviderSubscription listen( ProviderListenable provider, void Function(StateT? previous, StateT next) listener, { bool fireImmediately = false, bool weak = false, void Function(Object error, StackTrace stackTrace)? onError, }) { assert( !(weak && fireImmediately), 'Cannot specify both weak and fireImmediately', ); final sub = provider._addListener( this, listener, weak: weak, onError: onError ?? defaultOnError, onDependencyMayHaveChanged: null, ); _handleFireImmediately(container, sub, fireImmediately: fireImmediately); sub.impl._listenedElement.addDependentSubscription(sub.impl); return sub; } ``` -------------------------------- ### Initialize ProviderScope at the root Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/ProviderScope/ProviderScope.html Wrap the root widget of the application with ProviderScope to enable Riverpod functionality. ```dart void main() { runApp( // Enabled Riverpod for the entire application ProviderScope( child: MyApp(), ), ); } ``` -------------------------------- ### select(OutT selector(InT value)) Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/ProviderListenableSelect.html The select method allows you to partially listen to a provider by providing a selector function that transforms the provider's value into a specific subset or property. ```APIDOC ## select(OutT selector(InT value)) ### Description Partially listen to a provider. This method allows you to subscribe to a specific property or transformation of the provider's state, reducing unnecessary rebuilds. ### Signature `ProviderListenable select(OutT selector(InT value))` ### Parameters - **selector** (Function) - Required - A function that takes the current value of the provider (InT) and returns the specific part of the state (OutT) to listen to. ### Returns - **ProviderListenable** - A new provider listenable that only notifies listeners when the selected value changes. ``` -------------------------------- ### overrideWith Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/AsyncNotifierProvider-class.html Overrides the provider with a new initialization function. ```APIDOC ## overrideWith(NotifierT create()) ### Description Allows overriding the provider's initialization logic with a new function, useful for testing or dependency injection. ### Parameters - **create** (NotifierT) - Required - The new function to initialize the notifier. ``` -------------------------------- ### ProviderTransformer Implementation Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/misc/ProviderTransformer/ProviderTransformer.html Shows the internal implementation of the constructor, initializing the state using the provided initState function. ```dart ProviderTransformer({ required this.listener, required ValueT Function(ProviderTransformer self) initState, this.onClose, }) { _state = AsyncResult.guard(() => initState(this)); } ``` -------------------------------- ### when Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/AsyncData-class.html Performs an action based on the state of the AsyncValue, providing specific handlers for data, error, and loading. ```APIDOC ## when ### Description Performs an action based on the state of the AsyncValue. ### Parameters - **skipLoadingOnReload** (bool) - Optional - Whether to skip loading state on reload. - **skipLoadingOnRefresh** (bool) - Optional - Whether to skip loading state on refresh. - **skipError** (bool) - Optional - Whether to skip error state. - **data** (Function) - Required - Handler for data value. - **error** (Function) - Required - Handler for error and stack trace. - **loading** (Function) - Required - Handler for loading state. ``` -------------------------------- ### Stream build() Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/StreamNotifier/build.html Initializes the StreamNotifier. This method is intended to be overridden to define the stream logic. It is safe to use ref.watch or ref.listen within this method, and it will re-execute if watched dependencies change. ```APIDOC ## Stream build() ### Description Initializes a StreamNotifier. This method is called to start the stream and can safely use `ref.watch` or `ref.listen` to react to state changes. If a dependency changes, `build` re-executes while the notifier instance is preserved. ### Signature `Stream build()` ### Behavior - If this method throws or returns a failing future, the error is caught and emitted as an `AsyncError`. - The method is marked `@visibleForOverriding` and must be implemented by subclasses. ``` -------------------------------- ### Implementation of read Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/ProviderContainer/read.html Shows the internal implementation of the read method, which temporarily listens to the provider to retrieve its value. ```dart StateT read(ProviderListenable provider) { final sub = listen(provider, (_, _) {}); try { return sub.readSafe().valueOrProviderException; } finally { sub.close(); } } ``` -------------------------------- ### WidgetRef.listen Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/WidgetRef/listen.html Listen to a provider and execute a listener callback whenever its value changes. The listener is automatically removed when the widget rebuilds or is disposed. ```APIDOC ## void listen(ProviderListenable provider, void listener(StateT? previous, StateT next), {void onError(Object error, StackTrace stackTrace)?, bool weak = false}) ### Description Listen to a provider and call `listener` whenever its value changes. This method handles the removal of the listener automatically. ### Parameters - **provider** (ProviderListenable) - Required - The provider to listen to. - **listener** (void Function(StateT? previous, StateT next)) - Required - The callback executed when the provider value changes. - **onError** (void Function(Object error, StackTrace stackTrace)) - Optional - Callback executed if the provider emits an error. - **weak** (bool) - Optional - Defaults to false. Determines if the listener is weak. ### Usage Example ```dart @override Widget build(BuildContext context, WidgetRef ref) { ref.listen(counterProvider, (prev, next) { print('Counter changed from $prev to $next'); }); return Container(); } ``` ``` -------------------------------- ### Watch a family provider with parameters Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/StreamNotifierProvider/family-constant.html Illustrates the incorrect way to watch a family provider versus the correct way by passing a parameter. ```dart Widget build(BuildContext context, WidgetRef ref) { // Error – messagesFamily is not a provider final response = ref.watch(messagesFamily); } ``` ```dart Widget build(BuildContext context, WidgetRef ref) { final response = ref.watch(messagesFamily('id')); } ``` -------------------------------- ### overrideWith(Stream create(Ref ref, ArgT arg)) Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/misc/StreamProviderFamily-class.html Overrides the provider with a new initialization function. ```APIDOC ## overrideWith(Stream create(Ref ref, ArgT arg)) ### Description Override the provider with a new initialization function. ### Signature `Override overrideWith(Stream create(Ref ref, ArgT arg))` ``` -------------------------------- ### overrideWith2(NotifierT create(ArgT arg)) Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/misc/NotifierProviderFamily/overrideWith2.html Overrides the provider family with a new initialization function. This method is used to replace the implementation of a provider, often for testing purposes or to handle different environments. ```APIDOC ## overrideWith2 ### Description Overrides the provider family with a new initialization function. This will disable the auto-scoping mechanism, meaning any `dependencies` specified by the overridden provider will have no effect. ### Signature `Override overrideWith2(NotifierT create(ArgT arg))` ### Parameters - **create** (Function) - Required - A function that takes an argument of type `ArgT` and returns a `NotifierT` instance. ### Usage Example ```dart final myService = Provider((ref) => MyService()); runApp( ProviderScope( overrides: [ myService.overrideWith((ref) { ref.watch('other'); return MyFakeService(); }), ], child: MyApp(), ), ); ``` ``` -------------------------------- ### Implement Consumer build method Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/Consumer/build.html Standard implementation of the build method for a Consumer widget. ```dart @override Widget build(BuildContext context, WidgetRef ref) { return builder(context, ref, child); } ``` -------------------------------- ### Implementation of build abstract method Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/Notifier/build.html The build method must be implemented by subclasses of Notifier to define the initial state. ```dart @visibleForOverriding ValueT build(); ``` -------------------------------- ### overrideWith(Create> create) Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/StreamProvider-class.html Overrides the provider with a new initialization function. ```APIDOC ## overrideWith ### Description Overrides the provider with a new initialization function, allowing for dependency injection or testing scenarios. ### Parameters - **create** (Create>) - Required - The new function to initialize the stream. ``` -------------------------------- ### call(ArgT argument) Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/misc/ProviderFamily-class.html Creates a specific Provider instance from an external argument. ```APIDOC ## call(ArgT argument) ### Description Creates a provider from an external value. This method is used to instantiate a specific provider within the family using the provided argument. ### Signature `Provider call(ArgT argument)` ### Parameters - **argument** (ArgT) - The argument used to create the provider instance. ``` -------------------------------- ### when Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/AsyncLoading-class.html Performs an action based on the state of the AsyncValue, providing specific handlers for data, error, and loading cases. ```APIDOC ## when ### Description Performs an action based on the state of the AsyncValue. ### Parameters - **skipLoadingOnReload** (bool) - Optional - Whether to skip loading state on reload. - **skipLoadingOnRefresh** (bool) - Optional - Whether to skip loading state on refresh. - **skipError** (bool) - Optional - Whether to skip error state. - **data** (Function) - Required - Callback for data state. - **error** (Function) - Required - Callback for error state. - **loading** (Function) - Required - Callback for loading state. ``` -------------------------------- ### overrideWith2 Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/misc/NotifierProviderFamily-class.html Overrides the provider with a new initialization function that accepts an argument. ```APIDOC ## overrideWith2(NotifierT create(ArgT arg)) ### Description Override the provider with a new initialization function that takes the family argument. ### Signature `Override overrideWith2(NotifierT create(ArgT arg))` ### Parameters - **create** (NotifierT Function(ArgT)) - The function used to initialize the Notifier, receiving the family argument. ``` -------------------------------- ### call(ArgT argument) Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/misc/NotifierProviderFamily-class.html Creates a NotifierProvider instance from an external argument. ```APIDOC ## call(ArgT argument) ### Description Creates a provider from an external value. ### Signature `NotifierProvider call(ArgT argument)` ### Parameters - **argument** (ArgT) - The argument used to create the specific provider instance. ``` -------------------------------- ### ConsumerWidget constructor Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/ConsumerWidget/ConsumerWidget.html The constructor for creating a new ConsumerWidget instance. ```APIDOC ## ConsumerWidget ### Description A base class for widgets that can listen to providers. It is the equivalent of a StatelessWidget that provides access to a WidgetRef for watching providers. ### Constructor `const ConsumerWidget({Key? key})` ### Parameters - **key** (Key?) - Optional - The widget key. ### Usage ```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); } } ``` ``` -------------------------------- ### when Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/AsyncError-class.html Performs an action based on the state of the AsyncValue, providing specific handlers for data, error, and loading. ```APIDOC ## when ### Description Performs an action based on the state of the AsyncValue. ### Parameters - **skipLoadingOnReload** (bool) - Optional - Whether to skip loading state on reload. - **skipLoadingOnRefresh** (bool) - Optional - Whether to skip loading state on refresh. - **skipError** (bool) - Optional - Whether to skip error state. - **data** (Function) - Required - Handler for data. - **error** (Function) - Required - Handler for error and stack trace. - **loading** (Function) - Required - Handler for loading state. ``` -------------------------------- ### AsyncNotifierProvider constructor Source: https://pub.dev/documentation/flutter_riverpod/3.3.1/flutter_riverpod/AsyncNotifierProvider/AsyncNotifierProvider.html Creates a provider that manages an AsyncNotifier. Unlike other providers, the ref is accessed directly within the notifier rather than passed as an argument. ```APIDOC ## AsyncNotifierProvider constructor ### Description A provider which creates and listens to an AsyncNotifier. This is similar to FutureProvider but allows for performing side-effects. ### Signature AsyncNotifierProvider, ValueT>( NotifierT _createNotifier(), { String? name, Iterable? dependencies, bool isAutoDispose = false, Retry? retry, }) ```