### Flutter Riverpod Counter Example Source: https://pub.dev/packages/flutter_riverpod/example Demonstrates a basic counter application using flutter_riverpod. It showcases how to declare a StateProvider, use ConsumerWidget to watch provider changes, and update the state using ref.read. This example requires the flutter and flutter_riverpod packages. ```dart import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/legacy.dart'; // A Counter example implemented with riverpod void main() { runApp( // Adding ProviderScope enables Riverpod for the entire project const ProviderScope(child: MyApp()), ); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp(home: Home()); } } /// Providers are declared globally and specify how to create a state final counterProvider = StateProvider((ref) => 0); class Home extends ConsumerWidget { const Home({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { return Scaffold( appBar: AppBar(title: const Text('Counter example')), body: Center( // Consumer is a builder widget that allows you to read providers. child: Consumer( builder: (context, ref, _) { final count = ref.watch(counterProvider); return Text('$count'); }, ), ), floatingActionButton: FloatingActionButton( // The read method is a utility to read a provider without listening to it onPressed: () => ref.read(counterProvider.notifier).state++, child: const Icon(Icons.add), ), ); } } ``` -------------------------------- ### Implementing onDispose logic (Flutter Riverpod) Source: https://pub.dev/packages/flutter_riverpod/changelog Provides an example of how to manage resource cleanup or state changes upon provider disposal using the `ref.onDispose` callback. ```dart Provider((ref) { var mounted = true; ref.onDispose(() => mounted = false); }); ``` -------------------------------- ### Fix exception on unmounting nested ProviderScope Source: https://pub.dev/packages/flutter_riverpod/changelog Addresses an issue where unmounting a nested `ProviderScope` could lead to an exception. This ensures proper cleanup and stability in nested provider setups. ```dart fixed a bug where unmounting a nested ProviderScope could cause an exception (#1400) ``` -------------------------------- ### Add flutter_riverpod Dependency (Flutter CLI) Source: https://pub.dev/packages/flutter_riverpod/install This command adds the flutter_riverpod package as a dependency to your Flutter project. It automatically updates your pubspec.yaml file and runs `flutter pub get`. ```bash flutter pub add flutter_riverpod ``` -------------------------------- ### Migrate dependOn to read/watch in Riverpod Source: https://pub.dev/packages/flutter_riverpod/changelog Demonstrates the removal of `ref.dependOn` and its replacement with `ref.read` or `ref.watch`. This simplifies dependency management within providers. ```dart final streamProvider = StreamProvider(...); final example = Provider((ref) { Future last = ref.dependOn(streamProvider).last; }); // Migrated to: final streamProvider = StreamProvider(...); final example = Provider((ref) { Future last = ref.watch(streamProvider.last); }); ``` -------------------------------- ### Update ConsumerWidget build and Consumer builder syntax (Flutter Riverpod) Source: https://pub.dev/packages/flutter_riverpod/changelog Demonstrates the updated syntax for interacting with providers in Flutter Riverpod. The `build` method of `ConsumerWidget` and the `builder` of `Consumer` now use `WidgetRef` instead of `ScopedReader` for accessing providers. ```dart class Example extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { int count = ref.watch(counterProvider); ... } } ``` -------------------------------- ### Building a StreamProvider with StreamNotifier (Riverpod Generator) Source: https://pub.dev/packages/flutter_riverpod/changelog Demonstrates how to use `StreamNotifier` and `StreamNotifierProvider` for building a `StreamProvider` with modification capabilities. This pattern is intended for use with `riverpod_generator`. ```dart @riverpod class Example extends _$Example { @override Stream build() { // TODO return some stream } } ``` -------------------------------- ### Listening to Provider Changes (Riverpod) Source: https://pub.dev/packages/flutter_riverpod/changelog Shows the recommended way to listen to changes in a provider using `ref.listen`. This replaces the deprecated `provider.stream` approach. ```dart ref.listen(provider, (_, value) {...}); ``` -------------------------------- ### Checking Provider Initialization (Riverpod) Source: https://pub.dev/packages/flutter_riverpod/changelog Shows how to use `Ref.exists` to determine if a provider has been initialized within the current scope. This is useful for conditional logic or avoiding errors. ```dart ref.exists(provider); ``` -------------------------------- ### Migrate AutoDispose and Family syntax in Riverpod Source: https://pub.dev/packages/flutter_riverpod/changelog Illustrates the syntax change for `AutoDispose` and `Family` providers in Riverpod. The new syntax uses named constructors, making it more consistent with other provider types. ```dart final myProvider = AutoDisposeStateNotifierProviderFamily((ref, id) { return MyStateNotifier(id: id); }); // Migrated to: final myProvider = StateNotifierProvider.autoDispose.family((ref, id) { return MyStateNotifier(id: id); }); ``` -------------------------------- ### Migrate Computed to Provider in Riverpod Source: https://pub.dev/packages/flutter_riverpod/changelog Demonstrates how to migrate from the old 'Computed' syntax to the new 'Provider' syntax in Riverpod. This change simplifies provider creation and state management by unifying provider types. ```dart final provider = Provider(...); final example = Computed((watch) { final value = watch(provider); return value; }); // Migrated to: final provider = Provider(...); final example = Provider((ref) { final value = ref.watch(provider); return value; }); ``` -------------------------------- ### Importing AutoDisposeProvider with Types (Flutter Riverpod) Source: https://pub.dev/packages/flutter_riverpod/changelog Shows how to import the implementation class of providers with modifiers like AutoDisposeProvider, which is useful when using the `always_specify_types` lint. This allows explicit type declaration for providers. ```dart import 'package:flutter_riverpod/all.dart'; final AutoDisposeStateProvider counter = StateProvider.autoDispose((ProviderRefBase ref) { return 0; }); ``` -------------------------------- ### Controlling UI Updates with AsyncValue Flags (Riverpod) Source: https://pub.dev/packages/flutter_riverpod/changelog Explains how to use `AsyncValue.when` with flags like `skipLoadingOnReload`, `skipLoadingOnRefresh`, and `skipError` to fine-tune when the UI updates based on `AsyncValue` states. ```dart AsyncValue.when(skipLoadingOnReload: bool, skipLoadingOnRefresh: bool, skipError: bool) ``` -------------------------------- ### Listen to Provider Changes with ref.listen (Flutter/Dart) Source: https://pub.dev/packages/flutter_riverpod/changelog Demonstrates how to use `ref.listen` to trigger actions when a provider's state changes. This is useful for side effects within providers or for reacting to state changes in widgets, such as showing modals. It replaces the deprecated `ProviderListener`. ```dart final counterProvider = StateNotifierProvider((ref) => Counter()); final anotherProvider = Provider((ref) { ref.listen(counterProvider, (previous, count) { print('counter changed from $previous to $count'); }); }); class Example extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { ref.listen(counterProvider, (previous, count) { // Show modal or perform other side effects showDialog(context: context, builder: (ctx) => AlertDialog(title: Text('Count changed'))); }); return Text('...'); // Widget content } } ``` -------------------------------- ### ConsumerWidget Implementation (Flutter Riverpod) Source: https://pub.dev/packages/flutter_riverpod/changelog Shows how to implement `ConsumerWidget` in Flutter Riverpod. This allows creating `StatelessWidget`s that can directly read providers using the `watch` method. ```dart class MyWidget extends ConsumerWidget { const MyWidget({Key? key}) : super(key: key); @override Widget build(BuildContext context, ScopedReader watch) { final value = watch(myProvider); return Text('$value'); } } ``` -------------------------------- ### Synchronously Combining Async Providers with AsyncValue.requireValue Source: https://pub.dev/packages/flutter_riverpod/changelog Demonstrates how to synchronously combine asynchronous providers using `AsyncValue.requireValue` within `FutureProvider` or `AsyncNotifier`. This approach is safe to use inside the initialization function of providers, allowing for cleaner handling of dependent asynchronous states. ```dart final sumProvider = FutureProvider((ref) { AsyncValue a = ref.watch(aProvider); AsyncValue b = ref.watch(bProvider); // The following is safe if used inside the init function of providers. return a.requireValue + b.requireValue; }) ``` -------------------------------- ### Migrate FutureProvider read to watch in Riverpod Source: https://pub.dev/packages/flutter_riverpod/changelog Illustrates the migration from using `ref.read` on a `FutureProvider` to using `ref.watch` on the `.future` property. This ensures the provider state updates when the future completes. ```dart final futureProvider = FutureProvider(...); final example = Provider((ref) { Future future = ref.read(futureProvider); }); // Migrated to: final futureProvider = FutureProvider(...); final example = Provider((ref) { Future future = ref.watch(futureProvider.future); }); ``` -------------------------------- ### Use ref.listen for provider changes (Flutter Riverpod) Source: https://pub.dev/packages/flutter_riverpod/changelog Illustrates the modern approach to listening for provider value changes in Flutter Riverpod using `ref.listen`. This replaces the deprecated `ProviderListener`. ```dart class Example extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { ref.listen(counter, (count) { print('count changed $count'); }); } } ``` -------------------------------- ### Defining Provider Dependencies (Dart) Source: https://pub.dev/packages/flutter_riverpod/changelog Illustrates how to explicitly define dependencies for a provider. By specifying the `dependencies` parameter, Riverpod can automatically handle overriding the dependent provider when the dependency is overridden. This is useful for managing provider relationships and ensuring correct behavior. ```dart final a = Provider((ref) => ...); final b = Provider((ref) => ref.watch(a), dependencies: [a]); ``` -------------------------------- ### Creating a FutureProvider from another Provider's Stream (Riverpod) Source: https://pub.dev/packages/flutter_riverpod/changelog Illustrates how to create a `FutureProvider` that transforms data from another provider's stream. This is an alternative to using `StreamProvider` with `.map`. ```dart final a = FutureProvider((ref) async { final e = await ref.watch(b.future); return Model(e); }) ``` -------------------------------- ### Filter rebuilds with provider.select (Flutter Riverpod) Source: https://pub.dev/packages/flutter_riverpod/changelog Shows how to optimize widget rebuilds in Flutter Riverpod by using the `.select` method on providers. This allows a `Consumer` to rebuild only when a specific part of the provider's value changes. ```dart final userProvider = StateNotifierProvider(...); Consumer( builder: (context, ref, _) { // With this syntax, the Consumer will not rebuild if `userProvider` // emits a new User but its "name" didn't change. bool userName = ref.watch(userProvider.select((user) => user.name)); }, ) ``` -------------------------------- ### Listen to provider changes in another provider (Flutter Riverpod) Source: https://pub.dev/packages/flutter_riverpod/changelog Demonstrates how to use ref.listen within a provider to react to changes in another provider's state without recreating the listening provider. ```dart final counter = StateNotifierProvider(...); final anotherProvider = Provider((ref) { ref.listen(counter, (count) { print('counter change: $count'); }); }); ``` -------------------------------- ### Define provider dependencies (Flutter Riverpod) Source: https://pub.dev/packages/flutter_riverpod/changelog Shows how to specify dependencies for providers in Flutter Riverpod using the `dependencies` parameter. This enables automatic overriding of a provider when its dependencies are overridden. ```dart final a = Provider(...); final b = Provider((ref) => ref.watch(a), dependencies: [a]); ``` -------------------------------- ### Differentiating Rebuilds with AsyncValue.copyWithPrevious (Riverpod) Source: https://pub.dev/packages/flutter_riverpod/changelog Shows how to use `AsyncValue.copyWithPrevious` with the `isRefresh` flag to distinguish between rebuilds triggered by `ref.watch` and those triggered by `ref.refresh`. ```dart AsyncValue.copyWithPrevious(..., isRefresh: false) ``` -------------------------------- ### Await AsyncValue Providers with FutureProvider (Flutter/Dart) Source: https://pub.dev/packages/flutter_riverpod/changelog Illustrates how to await providers that emit `AsyncValue`, including `StateNotifierProvider` exposing `AsyncValue`. This allows `FutureProvider` to resolve with the state of an `AsyncValue` provider, simplifying asynchronous data fetching and state management. ```dart class MyAsyncStateNotifier extends StateNotifier> { MyAsyncStateNotifier(): super(AsyncValue.loading()) { // TODO fetch some data and update the state when it is obtained } } final myAsyncStateNotifierProvider = StateNotifierProvider>((ref) { return MyAsyncStateNotifier(); }); final someFutureProvider = FutureProvider((ref) async { // Await the future from the AsyncValue provider MyState myState = await ref.watch(myAsyncStateNotifierProvider.future); return myState; }); ``` -------------------------------- ### Consumer Widget Update (Flutter Riverpod) Source: https://pub.dev/packages/flutter_riverpod/changelog Demonstrates the updated syntax for the `Consumer` widget in Flutter Riverpod. The `watch` function is now accessed via the `builder` property, and an optional `child` parameter is available. ```dart return Consumer( builder: (context, watch, child) { final value = watch(myProvider); return Text('$value'); }, ); ``` -------------------------------- ### Migrate StreamProvider read to watch in Riverpod Source: https://pub.dev/packages/flutter_riverpod/changelog Shows the migration from using `ref.read` on a `StreamProvider` to using `ref.watch` on the `.stream` property. This change ensures that the provider rebuilds when the stream emits new values. ```dart final streamProvider = StreamProvider(...); final example = Provider((ref) { Stream stream = ref.read(streamProvider); }); // Migrated to: final streamProvider = StreamProvider(...); final example = Provider((ref) { Stream stream = ref.watch(streamProvider.stream); }); ``` -------------------------------- ### Update ConsumerWidget build method signature (Flutter Riverpod) Source: https://pub.dev/packages/flutter_riverpod/changelog Demonstrates the change in the build method signature for ConsumerWidget. The 'watch' parameter has been replaced with 'ref' for accessing providers. ```dart class Example extends ConsumerWidget { @override Widget build(BuildContext context, ScopedReader watch) { int count = watch(counterProvider); ... } } class Example extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { int count = ref.watch(counterProvider); ... } } ``` -------------------------------- ### Provider ref access to state and onDispose (Flutter Riverpod) Source: https://pub.dev/packages/flutter_riverpod/changelog Illustrates how to access the `state` property and use `onDispose` within provider definitions in Flutter Riverpod. The `ref` object provides access to the provider's state and lifecycle methods. ```dart Provider((ref) { ref.listen(onIncrementProvider, (_) { ref.state++; }); return 0; }); Provider((ref) { var mounted = true; ref.onDispose(() => mounted = false); }); ``` -------------------------------- ### Override family providers with a new provider (Flutter Riverpod) Source: https://pub.dev/packages/flutter_riverpod/changelog Demonstrates the updated syntax for overriding family providers in Flutter Riverpod. `overrideWithProvider` now requires creating a new `Provider` instance within the override. ```dart final family = Provider.family(...); family.overrideWithProvider( (Arg arg) => Provider((ref) => ...) ); ``` -------------------------------- ### Listen to Provider changes with ProviderContainer in Riverpod Source: https://pub.dev/packages/flutter_riverpod/changelog Shows how to listen to provider changes using `ProviderContainer.listen`. This replaces the older `Provider.watchOwner` method and provides a more structured way to observe provider state. ```dart ProviderContainer container; final provider = Provider((ref) => 0); final subscription = container.listen( provider, mayHaveChanged: (sub) {}, didChange: (sub) { }. ); subscription.close(); ``` -------------------------------- ### ScopedProvider Null Initialization (Flutter Riverpod) Source: https://pub.dev/packages/flutter_riverpod/changelog Illustrates initializing a `ScopedProvider` with `null` in Flutter Riverpod. This is equivalent to providing a function that throws an `UnimplementedError`. ```dart final example = ScopedProvider(null); ``` ```dart final example = ScopedProvider((watch) => throw UnimplementedError('')); ``` -------------------------------- ### Provider parameter types (Flutter Riverpod) Source: https://pub.dev/packages/flutter_riverpod/changelog Shows the updated parameter types for various providers, now accepting custom subclasses of ProviderRefBase for enhanced functionality. ```dart Provider((ProviderRef ref) {...}); FutureProvider((FutureProviderRef ref) {...}); StateProvider((StateProviderRef ref) {...}); ``` -------------------------------- ### FutureProvider and StreamProvider Loading State with Previous Value (Dart) Source: https://pub.dev/packages/flutter_riverpod/changelog Demonstrates how FutureProvider and StreamProvider expose the latest value during loading states through AsyncValue. This allows the UI to display previous data while new data is being fetched, preventing a jarring spinner. It shows the usage within a Riverpod consumer widget. ```dart final provider = FutureProvider((ref) async { ref.watch(anotherProvider); // may cause `provider` to rebuild return fetchSomething(); }) ... Widget build(context, ref) { return ref.watch(provider).when( error: (err, stack, _) => Text('error'), data: (user) => Text('Hello ${user.name}'), loading: (previous) { if (previous is AsyncData) { return Text('loading ... (previous: ${previous.value.name})'); } return CircularProgressIndicator(); } ); } ``` -------------------------------- ### Refresh Provider State with ref.refresh (Flutter/Dart) Source: https://pub.dev/packages/flutter_riverpod/changelog Shows how to use `ref.refresh` within a provider to manually recompute its state. This provides a more direct way to refresh a provider compared to accessing `ref.container.refresh`. ```dart final myProvider = Provider((ref) { // ... provider logic ... return 'initial value'; }); final refreshProvider = Provider((ref) { ref.listen(myProvider, (_, __) => { /* ... */ }); // To refresh myProvider: ref.refresh(myProvider); }); ``` -------------------------------- ### Overriding a Provider with a State (Riverpod) Source: https://pub.dev/packages/flutter_riverpod/changelog Demonstrates how to override a provider's behavior by providing a specific state using `provider.overrideWith((ref) => state)`. This is a newer, preferred method over `overrideWithProvider`. ```dart provider.overrideWith((ref) => state); ``` -------------------------------- ### Accessing and modifying provider state (Flutter Riverpod) Source: https://pub.dev/packages/flutter_riverpod/changelog Illustrates how to access and modify the state of a provider directly using `ref.state` within the provider's definition. ```dart Provider((ref) { ref.listen(onIncrementProvider, (_) { ref.state++; }); return 0; }); ``` -------------------------------- ### Update StateNotifierProvider Syntax (Flutter Riverpod) Source: https://pub.dev/packages/flutter_riverpod/changelog Demonstrates the syntax change for StateNotifierProvider in flutter_riverpod. The update affects how the provider is declared and how its notifier and state are accessed within a build method. ```dart class MyStateNotifier extends StateNotifier {...} final provider = StateNotifierProvider>((ref) => MyStateNotifier()); ... Widget build(context, watch) { MyStateNotifier notifier = watch(provider.notifier); MyModel model = watch(provider); } ``` -------------------------------- ### Fix null exception on web Source: https://pub.dev/packages/flutter_riverpod/changelog Addresses a null exception that occurred specifically on the web platform. This improves the compatibility and stability of Riverpod on the web. ```dart Fixed a null exception on web ``` -------------------------------- ### Improve dependency assert performance Source: https://pub.dev/packages/flutter_riverpod/changelog Enhances the performance of the assertion that verifies providers correctly respect their `dependencies` variable. This speeds up development builds where these assertions are active. ```dart Improved the performance of the assert which verifies that providers properly respect their `dependencies` variable. ``` -------------------------------- ### Add WidgetRef.listenManual in Flutter Source: https://pub.dev/packages/flutter_riverpod/changelog Introduces `WidgetRef.listenManual` for listening to providers outside the `build` method in a widget. This provides more flexibility for managing provider subscriptions in Flutter. ```dart Added `WidgetRef.listenManual` for listening to providers in a widget outside of `build`. ``` -------------------------------- ### Add side-effect listeners for provider lifecycle events Source: https://pub.dev/packages/flutter_riverpod/changelog Introduces `ref.onAddListener`, `ref.onRemoveListener`, `ref.onCancel`, and `ref.onResume` to perform side effects when providers are listened to or stop being listened. This enhances control over provider lifecycle management. ```dart Added `ref.onAddListener`, `ref.onRemoveListener`, `ref.onCancel` and `ref.onResume`. All of which allow performing side-effects when providers are listened or stop being listened. ``` -------------------------------- ### Add WidgetRef.context in Flutter Source: https://pub.dev/packages/flutter_riverpod/changelog Introduces `WidgetRef.context` allowing functions dependent on `WidgetRef` to access `BuildContext` without explicit parameter passing. This enhances convenience in Flutter development with Riverpod. ```dart Added `WidgetRef.context`. This allows functions that depend on a `WidgetRef` to use the `BuildContext` without having to receive it as parameter. ``` -------------------------------- ### Add provider.selectAsync in Flutter Source: https://pub.dev/packages/flutter_riverpod/changelog Introduces `provider.selectAsync` for awaiting asynchronous values while filtering rebuilds. This feature improves performance by preventing unnecessary widget updates in Flutter applications using Riverpod. ```dart Added `provider.selectAsync`, which allows to both await an async value while also filtering rebuilds. ``` -------------------------------- ### StateProvider/StateNotifierProvider listener optimization Source: https://pub.dev/packages/flutter_riverpod/changelog Optimizes `StateProvider` and `StateNotifierProvider` to not notify listeners on `ref.refresh` if the new result is identical to the old one. This reduces unnecessary rebuilds and improves performance. ```dart `StateProvider` and `StateNotifierProvider` no longer notify their listeners on `ref.refresh` if the new result is identical to the old one. ``` -------------------------------- ### Listen to Async Data in Flutter UI with Riverpod (Dart) Source: https://pub.dev/packages/flutter_riverpod/index This code snippet shows how to consume an asynchronous data stream provided by Riverpod within a Flutter `ConsumerWidget`. It uses `ref.watch` to observe the `boredSuggestionProvider` and a `switch` statement to gracefully handle different states: `AsyncData` (data loaded), `AsyncError` (an error occurred), and the default loading state. ```dart class Home extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final boredSuggestion = ref.watch(boredSuggestionProvider); // Perform a switch-case on the result to handle loading/error states return switch (boredSuggestion) { AsyncData(:final value) => Text('data: $value'), AsyncError(:final error) => Text('error: $error'), _ => const Text('loading'), }; } } ``` -------------------------------- ### Add ref.listenSelf for provider-internal listening Source: https://pub.dev/packages/flutter_riverpod/changelog Introduces `ref.listenSelf` allowing a provider to subscribe to its own changes. This is useful for side effects like logging or persisting state within the provider itself. ```dart Added `ref.listenSelf`, for subscribing to changes of a provider within that provider. That can be useful for logging purposes or storing the state of a provider in a DB. ``` -------------------------------- ### Fix ProviderObserver.didDisposeProvider execution Source: https://pub.dev/packages/flutter_riverpod/changelog Ensures that `ProviderObserver.didDisposeProvider` is correctly executed when a provider is refreshed. This fixes an issue with lifecycle event tracking. ```dart Fix `ProviderObserver.didDisposeProvider` not executing on provider refresh. ``` -------------------------------- ### Fix potential null exception with autoDispose Source: https://pub.dev/packages/flutter_riverpod/changelog Resolves a potential null exception that could occur when using the `autoDispose` feature in Riverpod. This improves the stability of auto-disposing providers. ```dart fixed potential null exception when using `autoDispose` ``` -------------------------------- ### Fix refresh for provider.future/stream Source: https://pub.dev/packages/flutter_riverpod/changelog Corrects an issue where refreshing `provider.future` or `provider.stream` did not work as expected. This ensures proper refreshing of asynchronous providers. ```dart Fixed an issue where refreshing a `provider.future`/`provider.stream` did work properly ``` -------------------------------- ### Fix onDispose listener execution with autoDispose Source: https://pub.dev/packages/flutter_riverpod/changelog Addresses a bug where `onDispose` listeners could be executed twice under certain conditions when using `autoDispose`. This ensures correct disposal logic. ```dart Fixed a bug where `onDispose` listeners could be executed twice under certain conditions when using `autoDispose`. ``` -------------------------------- ### Fix false positive with ref.watch asserts Source: https://pub.dev/packages/flutter_riverpod/changelog Resolves a false positive issue with `ref.watch` assertions. This improves the reliability of assertion checks during development. ```dart Fixed false positive with `ref.watch` asserts ``` -------------------------------- ### Await Provider Notifications with ProviderContainer.pump (Flutter/Dart) Source: https://pub.dev/packages/flutter_riverpod/changelog Introduces `ProviderContainer.pump` as a utility to wait until providers notify their listeners or are disposed. This is particularly useful for testing asynchronous operations and ensuring state consistency before proceeding. ```dart final container = ProviderContainer(); // Assume someProvider is defined and might take time to update await container.pump(someProvider); // Now you can safely read the updated state of someProvider ``` -------------------------------- ### Obtaining Value from AsyncValue (Riverpod) Source: https://pub.dev/packages/flutter_riverpod/changelog Demonstrates the use of `AsyncValue.requireValue` to forcibly extract the data from an `AsyncValue`. This method will throw an error if the `AsyncValue` is in a loading or error state. ```dart AsyncValue.requireValue ``` -------------------------------- ### Import flutter_riverpod in Dart Code Source: https://pub.dev/packages/flutter_riverpod/install This import statement allows you to use the functionalities provided by the flutter_riverpod package in your Dart code. Ensure the package is added as a dependency first. ```dart import 'package:flutter_riverpod/flutter_riverpod.dart'; ``` -------------------------------- ### Fixing Assert Error with Self-Dependent Families (Riverpod) Source: https://pub.dev/packages/flutter_riverpod/changelog Addresses a specific bug where an assert error could occur if a provider `family` depended on itself while also specifying `dependencies`. This fix ensures correct behavior in such scenarios. ```dart # FIX : Fixed an assert error if a `family` depends on itself while specifying `dependencies`. (#1721). ``` -------------------------------- ### Define Async Network Request with @riverpod Annotation (Dart) Source: https://pub.dev/packages/flutter_riverpod/index This snippet demonstrates how to define an asynchronous network request using the `@riverpod` annotation in Dart. It fetches data from an external API and returns the result as a Future. This approach helps in managing asynchronous operations and their states within the Riverpod framework. ```dart @riverpod Future boredSuggestion(Ref ref) async { final response = await http.get( Uri.https('boredapi.com', '/api/activity'), ); final json = jsonDecode(response.body); return json['activity']! as String; } ``` -------------------------------- ### Avoid ref.watch/read inside selectors (Flutter Riverpod) Source: https://pub.dev/packages/flutter_riverpod/changelog Highlights a restriction in Flutter Riverpod where `ref.watch` or `ref.read` cannot be used inside a provider's selector function. This prevents potential issues with rebuild logic. ```dart provider.select((value) => ref.watch(something)); // KO, cannot user ref.watch inside selectors ``` -------------------------------- ### Update state with StateController.update (Flutter Riverpod) Source: https://pub.dev/packages/flutter_riverpod/changelog Demonstrates the simplified state update mechanism in Flutter Riverpod using `StateController.update`. This method allows updating the state based on its previous value. ```dart final provider = StateController((ref) => 0); ... ref.read(provider).update((state) => state + 1); ``` -------------------------------- ### Add new AsyncValue functionalities Source: https://pub.dev/packages/flutter_riverpod/changelog Enhances `AsyncValue` with new properties and methods including `hasError`, `hasData`, `asError`, `isLoading`, `copyWithPrevious`, and `unwrapPrevious`. These additions provide more granular control and information about asynchronous states. ```dart Added new functionalities to `AsyncValue`: `hasError`, `hasData`, `asError`, `isLoading` , `copyWithPrevious` and `unwrapPrevious`. ``` -------------------------------- ### Add container.invalidate and ref.invalidate in Riverpod Source: https://pub.dev/packages/flutter_riverpod/changelog Introduces `container.invalidate(provider)` and `ref.invalidate(provider)` for invalidating providers without immediate rebuilds. These are safer alternatives to `ref.refresh` for managing provider states. ```dart Added `container.invalidate(provider)`/`ref.invalidate(provider)` and `ref.invalidateSelf()`. These are similar to `ref.refresh` methods, but do not immediately rebuild the provider. ``` -------------------------------- ### Fix AsyncValue.value throwing on error Source: https://pub.dev/packages/flutter_riverpod/changelog Corrects an issue where `AsyncValue.value` did not throw an exception when an error occurred. This ensures that errors are properly propagated and handled. ```dart Fixed an issue where `AsyncValue.value` did not throw if there is an error. ``` -------------------------------- ### Remove assert for multiple provider overrides Source: https://pub.dev/packages/flutter_riverpod/changelog Removes an assert that prevented overriding the same provider or family multiple times on a `ProviderScope` or `ProviderContainer`. This allows for more flexible provider management. ```dart Removed an assert preventing from overriding the same provider/family multiple times on a `ProviderScope`/`ProviderContainer`. ``` -------------------------------- ### Add support for ref.invalidate(family) in Riverpod Source: https://pub.dev/packages/flutter_riverpod/changelog Adds support for `ref.invalidate(family)` to recompute an entire provider family. This simplifies the management of state for families of providers. ```dart Add support for `ref.invalidate(family)` to recompute an entire family (#1517) ``` -------------------------------- ### Fix providers depending on themselves with autoDispose Source: https://pub.dev/packages/flutter_riverpod/changelog Corrects a bug that allowed providers to incorrectly depend on themselves, which could break `autoDispose` functionality. This ensures correct dependency management and auto-disposal behavior. ```dart Fixed an issue where providers were incorrectly allowed to depend on themselves, breaking `autoDispose` in the process. ``` -------------------------------- ### Fix AsyncValue.whenData preserving state Source: https://pub.dev/packages/flutter_riverpod/changelog Corrects a bug where `AsyncValue.whenData` did not preserve the `AsyncValue.isLoading` or `AsyncValue.isRefreshing` states. This ensures consistent UI updates during asynchronous operations. ```dart fixed a bug where `AsyncValue.whenData` did not preserve `AsyncValue.isLoading/isRefreshing` ``` -------------------------------- ### Add AsyncValue.valueOrNull in Riverpod Source: https://pub.dev/packages/flutter_riverpod/changelog Introduces `AsyncValue.valueOrNull` to safely retrieve the value from an `AsyncValue` while ignoring potential errors. This simplifies error handling for asynchronous operations. ```dart Added `AsyncValue.valueOrNull` to obtain the value while ignoring potential errors. ``` -------------------------------- ### Add AutoDisposeRef.keepAlive() in Riverpod Source: https://pub.dev/packages/flutter_riverpod/changelog Introduces `AutoDisposeRef.keepAlive()` as a replacement for `AutoDisposeRef.maintainState`. This function provides a more reusable way to prevent provider disposal in auto-disposing providers. ```dart A new `AutoDisposeRef.keepAlive()` function is added. It is meant to replace `AutoDisposeRef.maintainState` to make logic for preventing the disposal of a provider more reusable. ``` -------------------------------- ### Fix cast error when overriding provider types Source: https://pub.dev/packages/flutter_riverpod/changelog Resolves a cast error that occurred when overriding a provider with a more specific provider type. This ensures type safety during provider overrides. ```dart Fixed a cast error when overriding a provider with a more specific provider type (#1100) ``` -------------------------------- ### Fix memory leak in StateProvider.autoDispose .state Source: https://pub.dev/packages/flutter_riverpod/changelog Resolves a memory leak issue specifically related to the `.state` property of `StateProvider.autoDispose`. This improves memory management for auto-disposing state providers. ```dart Fixed a memory leak when using `StateProvider.autoDispose`'s `.state` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.