### void mutationStart(ProviderObserverContext context, Mutation mutation) Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/ProviderObserver/mutationStart.html This method is called when a mutation starts. It provides the ProviderObserverContext and the Mutation object as a convenience. ```APIDOC ## mutationStart ### Description A lifecycle method triggered when a mutation starts. The `mutation` parameter is guaranteed to be the same as `ProviderObserverContext.mutation`. ### Signature `void mutationStart(ProviderObserverContext context, Mutation mutation)` ### Parameters - **context** (ProviderObserverContext) - The context of the provider observer. - **mutation** (Mutation) - The mutation instance that has started. ``` -------------------------------- ### Registering an event handler in a Bloc Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/Bloc/on.html Example of defining a Bloc and registering an event handler for a specific event type using the on method. ```dart abstract class CounterEvent {} class CounterIncrementPressed extends CounterEvent {} class CounterBloc extends Bloc { CounterBloc() : super(0) { on((event, emit) => emit(state + 1)); } } ``` -------------------------------- ### bool get isClosed Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/Closable/isClosed.html Returns a boolean indicating if the object is closed. ```APIDOC ## bool get isClosed ### Description Returns a boolean value indicating whether the object is closed. An object is considered closed once the close method has been called. ### Signature `bool get isClosed` ### Returns - **bool** - True if the object is closed, false otherwise. ``` -------------------------------- ### Transition(currentState, event, nextState) Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/Transition-class.html Constructor for creating a new Transition instance representing a state change. ```APIDOC ## Transition(currentState, event, nextState) ### Description Creates a new Transition instance which represents the change from one state to another, consisting of the current state, the event that triggered the change, and the resulting next state. ### Constructor Signature `const Transition({required State currentState, required Event event, required State nextState})` ### Parameters - **currentState** (State) - Required - The current state at the time of the change. - **event** (Event) - Required - The event which triggered the transition. - **nextState** (State) - Required - The next state resulting from the transition. ``` -------------------------------- ### Define a ChangeNotifier provider Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/ProviderListenableSelect/select.html Example of a ChangeNotifier class and its corresponding provider definition. ```dart class Person extends ChangeNotifier { int _age = 0; int get age => _age; set age(int age) { _age = age; notifyListeners(); } String _name = ''; String get name => _name; set name(String name) { _name = name; notifyListeners(); } } final personProvider = ChangeNotifierProvider((_) => Person()); ``` -------------------------------- ### StackTrace? get stackTrace Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/AsyncValue/stackTrace.html Retrieves the stack trace of the error if the AsyncValue is in an error state. ```APIDOC ## Property: stackTrace ### Description Returns the stack trace associated with the error if the AsyncValue is in an error state. Returns null if there is no error. ### Signature `StackTrace? get stackTrace` ### Returns - **StackTrace?** - The stack trace of the error, or null if no error exists. ``` -------------------------------- ### MultiBlocObserver.new Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/MultiBlocObserver/MultiBlocObserver.html Creates a new MultiBlocObserver instance that delegates events to a list of provided BlocObserver instances. ```APIDOC ## MultiBlocObserver.new ### Description A BlocObserver which supports registering multiple BlocObserver instances. This is useful when maintaining multiple BlocObserver instances for different functions e.g. LoggingBlocObserver, ErrorReportingBlocObserver. ### Constructor Signature const MultiBlocObserver({required List observers}) ### Parameters - **observers** (List) - Required - A list of BlocObserver instances to be registered. ### Usage Example ```dart Bloc.observer = MultiBlocObserver( observers: [ LoggingObserver(), ErrorObserver(), PerformanceObserver(), ], ); ``` ``` -------------------------------- ### Initialize MultiBlocObserver Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/MultiBlocObserver/MultiBlocObserver.html Assign a list of multiple observers to the global Bloc.observer property. ```dart Bloc.observer = MultiBlocObserver( observers: [ LoggingObserver(), ErrorObserver(), PerformanceObserver(), ], ); ``` -------------------------------- ### Using notifyListeners in a Notifier Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/Ref/notifyListeners.html Example of calling notifyListeners after modifying a mutable state list. ```dart class TodoList extends Notifier> { @override List> build() => []; void addTodo(Todo todo) { state.add(todo); ref.notifyListeners(); } } ``` -------------------------------- ### Implementation of mutationStart Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/ProviderObserver/mutationStart.html Defines the signature and structure for the mutationStart lifecycle hook. ```dart void mutationStart( ProviderObserverContext context, Mutation mutation, ) {} ``` -------------------------------- ### Define a CounterCubit Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/Cubit/Cubit.html Example of extending Cubit to manage an integer state with an increment method. ```dart class CounterCubit extends Cubit { CounterCubit() : super(0); void increment() => emit(state + 1); } ``` -------------------------------- ### bool get isLoading Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/AsyncValueExtensions/isLoading.html A getter that returns true if an asynchronous loading operation is currently in progress. ```APIDOC ## bool get isLoading ### Description Returns a boolean indicating whether a new value is currently being loaded asynchronously. Note that this property can be true even if `hasValue` or `hasError` are also true. ### Signature `bool get isLoading` ### Returns - **bool**: True if an asynchronous loading operation is active, false otherwise. ``` -------------------------------- ### void onCreate(BlocBase bloc) Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/BlocObserver/onCreate.html Called whenever a Bloc is instantiated. This method is useful for observing the exact moment a cubit or bloc instance is created. ```APIDOC ## void onCreate(BlocBase bloc) ### Description Called whenever a Bloc is instantiated. In many cases, a cubit may be lazily instantiated and onCreate can be used to observe exactly when the cubit instance is created. ### Signature `void onCreate(BlocBase bloc)` ### Parameters - **bloc** (BlocBase) - The instance of the Bloc or Cubit that was created. ### Annotations - **@protected** - **@mustCallSuper** ``` -------------------------------- ### Implementation of allProviders Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/ProviderContainer/allProviders.html The internal implementation of allProviders, showing how it handles family filtering and parent container traversal. ```dart Iterable allProviders({Family? family}) { final providers = family != null ? _pointerManager.listFamilyProviders(family) : _pointerManager.listProviders(); if (container.parent case final parent?) { return providers.followedBy(parent.allProviders(family: family)); } return providers; } ``` -------------------------------- ### Get state implementation Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/AsyncNotifier/state.html The getter for the current state value, marked for testing and internal use. ```dart @visibleForTesting @protected @override AsyncValue get state; ``` -------------------------------- ### bool get isDone Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/Emitter/isDone.html Returns a boolean value indicating the completion or cancellation status of the EventHandler associated with the Emitter. ```APIDOC ## bool get isDone ### Description Returns whether the EventHandler associated with this Emitter has been completed or canceled. ### Signature `bool get isDone` ### Returns - **bool**: True if the EventHandler is completed or canceled, otherwise false. ``` -------------------------------- ### BlocProvider Constructor Implementation Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/BlocProvider/BlocProvider.html The implementation of the BlocProvider constructor, showing the required parameters and superclass initialization. ```dart BlocProvider( this._create, { super.name, super.dependencies, super.isAutoDispose = false, super.retry, }) : super( $allTransitiveDependencies: computeAllTransitiveDependencies( dependencies, ), from: null, argument: null, ); ``` -------------------------------- ### bool get hasValue Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/AsyncValueExtensions/hasValue.html A getter that returns true if the value is set, regardless of the loading or error state of the AsyncValue. ```APIDOC ## bool get hasValue ### Description Returns a boolean indicating whether a value is set. Note that this property can be true even if the instance is currently in a loading state or contains an error. ### Signature `bool get hasValue` ### Returns - **bool** - True if the value is present, false otherwise. ``` -------------------------------- ### listen method Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/ProviderContainer/listen.html Listen to a provider and execute a callback whenever its value changes. Returns a subscription object for manual cancellation. ```APIDOC ## listen ### Description Listen to a provider and call `listener` whenever its value changes. Listeners are automatically removed when the provider rebuilds. Returns a `ProviderSubscription` object that allows cancelling the subscription early. ### 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) - Required - The provider to listen to. - **listener** (void Function(StateT? previous, StateT next)) - Required - Callback invoked when the provider value changes. - **fireImmediately** (bool) - Optional - If true, immediately calls the listener 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** (void Function(Object error, StackTrace stackTrace)) - Optional - Callback for uncaught errors in the provider. ### Returns - **ProviderSubscription** - An object that allows cancelling the subscription. ``` -------------------------------- ### Implement build abstract method Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/Notifier/build.html Use this method to initialize the Notifier. It is safe to use Ref.watch or Ref.listen within this scope. ```dart @visibleForOverriding ValueT build(); ``` -------------------------------- ### AsyncData? get asData Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/AsyncValueExtensions/asData.html Upcasts an AsyncValue into an AsyncData. Returns null if the current state is AsyncLoading or AsyncError. ```APIDOC ## asData ### Description Upcasts an AsyncValue into an AsyncData. Returns null if the AsyncValue is an AsyncLoading or AsyncError state. Note that an AsyncData may still be in a loading or error state, such as during a pull-to-refresh operation. ### Signature `AsyncData? get asData` ### Returns - **AsyncData?**: The data if the state is AsyncData, otherwise null. ``` -------------------------------- ### AsyncError? get asError Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/AsyncValueExtensions/asError.html Upcasts an AsyncValue into an AsyncError. Returns null if the AsyncValue is an AsyncLoading or AsyncData instance. ```APIDOC ## asError ### Description Upcasts an AsyncValue into an AsyncError. Returns null if the AsyncValue is an AsyncLoading or AsyncData instance. Note that an AsyncError may still be in a loading state, such as during a pull-to-refresh operation. ### Signature `AsyncError? get asError` ### Returns - **AsyncError?**: The error object if the state is an error, otherwise null. ``` -------------------------------- ### Implementing BlocProvider with a Cubit Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/BlocProvider-class.html Demonstrates defining a Cubit and exposing it via BlocProvider, with usage in a ConsumerWidget to watch state changes. ```dart class CounterCubit extends Cubit { CounterCubit(int state) : super(state); void increment() => emit(state + 1); } final counterCubitProvider = BlocProvider((ref) => CounterCubit(0)); class MyHomePage extends ConsumerWidget { const MyHomePage({Key? key, required this.title}) : super(key: key); final String title; @override Widget build(BuildContext context, WidgetRef ref) { // Rebuilds the widget if the cubit/bloc changes. // But does not rebuild if the state changes with the same cubit/bloc final counterCubit = ref.watch(counterCubitProvider.bloc); return Scaffold( appBar: AppBar( title: Text(title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'initial counterCubit.state: ${counterCubit.state}', ), Consumer(builder: (context, ref, __) { // Rebuilds on every emitted state final _counter = ref.watch(counterCubitProvider); return Text( '$_counter', style: Theme.of(context).textTheme.headline4, ); }), ], ), ), floatingActionButton: FloatingActionButton( onPressed: () { ref.read(counterCubitProvider.bloc).increment(); } tooltip: 'Increment', child: Icon(Icons.add), ), ); } } ``` -------------------------------- ### Transition constructor Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/Transition/Transition.html Creates a new Transition instance representing the change from one state to another triggered by an event. ```APIDOC ## Transition constructor ### Description Creates a new instance of a Transition, which encapsulates the state transition process in a bloc. ### Signature `const Transition({required State currentState, required Event event, required State nextState})` ### Parameters - **currentState** (State) - Required - The state before the transition occurred. - **event** (Event) - Required - The event that triggered the transition. - **nextState** (State) - Required - The state after the transition occurred. ``` -------------------------------- ### num? get progress Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/AsyncValueExtensions/progress.html Retrieves the current progress of an asynchronous operation. The value is a number between 0 and 1, or null if not set. ```APIDOC ## num? get progress ### Description Returns the current progress of the asynchronous operation. The value is expected to be between 0 and 1. If no progress has been set, it returns null. ### Usage ```dart // Accessing the progress property final currentProgress = asyncValue.progress; // Setting progress in a Notifier state = AsyncLoading(progress: 0); await something(); ref.state = AsyncLoading(progress: 1); ``` ``` -------------------------------- ### Implement BLoC with Riverpod Source: https://pub.dev/packages/riverbloc Defines a Cubit and exposes it via a BlocProvider, demonstrating how to watch the bloc instance and its state within a ConsumerWidget. ```dart class CounterCubit extends Cubit { CounterCubit(int state) : super(state); void increment() => emit(state + 1); } final counterProvider = BlocProvider( (ref) => CounterCubit(0), ); class MyHomePage extends ConsumerWidget { const MyHomePage({Key? key, this.title}) : super(key: key); final String title; @override Widget build(BuildContext context, WidgetRef ref) { // Rebuilds the widget if the cubit/bloc changes. // But does not rebuild if the state changes with the same cubit/bloc final counterCubit = ref.watch(counterProvider.bloc); return Scaffold( appBar: AppBar( title: Text(title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'initial counterCubit.state: ${counterCubit.state}', ), Consumer(builder: (context, watch, __) { // Rebuilds in every emitted state final _counter = ref.watch(counterProvider); return Text( '$_counter', style: Theme.of(context).textTheme.headline4, ); }), Consumer( builder: (context, ref, __) { final _counter = ref.watch( counterProvider .when((prev, curr) => (curr + prev) % 5 == 0) .select((state) => 2 * state), ); return Text( '$_counter', style: Theme.of(context).textTheme.headline4, ); }, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: () => ref.read(counterProvider.bloc).increment(), tooltip: 'Increment', child: Icon(Icons.add), ), ); } } ``` -------------------------------- ### bool get hasError Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/AsyncValueExtensions/hasError.html A getter that returns true if the error property is not null. Note that this can be true simultaneously with hasValue or isLoading. ```APIDOC ## bool get hasError ### Description Returns a boolean indicating whether the current AsyncValue contains an error. Even if hasError is true, it is still possible for hasValue or isLoading to also be true. ### Signature `bool get hasError` ``` -------------------------------- ### Incorrect usage of family provider Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/AsyncNotifierProvider/family-constant.html Example of an invalid attempt to watch a family provider without passing the required parameter. ```dart Widget build(BuildContext context, WidgetRef ref) { // Error – messagesFamily is not a provider final response = ref.watch(messagesFamily); } ``` -------------------------------- ### Implement the build method Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/StreamNotifier/build.html Use this signature to define the initialization logic for a StreamNotifier. ```dart @visibleForOverriding Stream build(); ``` -------------------------------- ### bool get isClosed Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/Bloc/isClosed.html Returns a boolean value indicating if the bloc is closed. A bloc is considered closed once the close method has been invoked. ```APIDOC ## bool get isClosed ### Description Returns whether the bloc is closed. A bloc is considered closed once close is called, and subsequent state changes cannot occur. ### Returns - **bool** - True if the bloc is closed, false otherwise. ``` -------------------------------- ### listen method signature Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/Ref/listen.html The definition of the listen method, showing parameters for provider subscription, listener callbacks, and configuration flags. ```dart @override ProviderSubscription listen( ProviderListenable provider, void listener( StateT? previous, StateT next ), { void onError( Object error, StackTrace stackTrace )?, bool weak = false, bool fireImmediately = false, }) ``` -------------------------------- ### bool get isReloading Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/AsyncValueExtensions/isReloading.html Returns true if the provider is recomputing because of a dependency change (using Ref.watch) after an initial value or error has been emitted. ```APIDOC ## isReloading ### Description A boolean property that returns true if the associated provider was recomputed because of a dependency change (using Ref.watch), after at least one value or error has been emitted. If the provider rebuilds due to Ref.invalidate or Ref.refresh, this property will be false (and isRefreshing will be true). ### Signature `bool get isReloading` ### Returns - **bool** - True if the provider is recomputing due to a dependency change, false otherwise. ``` -------------------------------- ### NotifierProvider constructor Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/NotifierProvider/NotifierProvider.html Initializes a new NotifierProvider instance to manage a synchronous Notifier. ```APIDOC ## NotifierProvider constructor ### Description Creates a provider that exposes a synchronous Notifier. This provider is used for state management where the state is mutable. ### Signature NotifierProvider, ValueT>( NotifierT _createNotifier(), { String? name, Iterable? dependencies, bool isAutoDispose = false, Retry? retry, }) ``` -------------------------------- ### call method Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/AutoDisposeBlocProviderFamilyBuilder/call.html Creates a BlocProviderFamily that builds its value based on an external parameter. ```APIDOC ## call, S, ArgT> ### Description Creates a group of providers that builds their value from an external parameter. This allows connecting a provider with values it does not have direct access to. ### Signature `BlocProviderFamily call, S, ArgT>(B create(Ref ref, ArgT param), {String? name, Iterable? dependencies, Retry? retry})` ### Parameters - **create** (Function) - Required - A function that receives a `Ref` and an `ArgT` parameter to construct the provider state. - **name** (String) - Optional - An optional identifier for the provider. - **dependencies** (Iterable) - Optional - A list of providers that this family depends on. - **retry** (Retry) - Optional - Configuration for retry logic. ### Usage Example ```dart final userFamily = FutureProvider.family((ref, userId) async { final userRepository = ref.read(userRepositoryProvider); return await userRepository.fetch(userId); }); // In a widget: final user = ref.watch(userFamily(userId)); ``` ``` -------------------------------- ### Override hashCode implementation Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/Transition/hashCode.html Example of overriding the hashCode getter to include relevant state fields, ensuring consistency with equality checks. ```dart @override int get hashCode => Object.hashAll([currentState, event, nextState]); ``` -------------------------------- ### BlocProvider constructor Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/BlocProvider/BlocProvider.html Initializes a new BlocProvider instance to manage a BLoC or Cubit. ```APIDOC ## BlocProvider constructor ### Description Creates a new BlocProvider instance. This provider is used to expose a BLoC or Cubit to the widget tree or other providers. ### Signature BlocProvider, S>( B _create(Ref ref), { String? name, Iterable? dependencies, bool isAutoDispose = false, Retry? retry, }) ``` -------------------------------- ### ValueT get value Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/AsyncData/value.html Accesses the current value. If the state is loading or error, it returns the previous value, or null if no previous value exists. ```APIDOC ## ValueT get value ### Description Returns the value currently exposed by the AsyncData instance. If the instance is in a loading or error state, it returns the previous value, or null if no previous value is available. ### Usage ```dart // Accessing the value directly final data = ref.watch(provider).value; // Accessing without previous value during loading/error final data = ref.watch(provider).unwrapPrevious().value; ``` ``` -------------------------------- ### Using selectAsync with FutureProvider Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/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 onCreate in MultiBlocObserver Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/MultiBlocObserver/onCreate.html This method iterates through all registered observers and notifies them that a new Bloc has been created. ```dart @override void onCreate(BlocBase bloc) { for (final observer in observers) { observer.onCreate(bloc); } } ``` -------------------------------- ### Creating an object dependent on multiple providers Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/Provider/Provider.html Demonstrates manual dependency injection by watching multiple providers within a 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)'; } ``` -------------------------------- ### bool get mounted Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/Ref/mounted.html A property that returns true if the Ref is active and false if it has been disposed. It is recommended to use this to check for disposal before continuing asynchronous operations. ```APIDOC ## bool get mounted ### Description Returns a boolean indicating whether the current Ref is still active. If false, the provider has been disposed and further operations should be halted to avoid race conditions. ### Usage ```dart final myProvider = FutureProvider((ref) async { await dio.get(..., cancelToken: cancelToken); if (!ref.mounted) throw Exception('cancelled'); return ...; }); ``` ``` -------------------------------- ### NotifierProvider Constructor Implementation Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/NotifierProvider/NotifierProvider.html The internal implementation of the NotifierProvider constructor, showing the initialization of dependencies and provider configuration. ```dart NotifierProvider( this._createNotifier, { super.name, super.dependencies, super.isAutoDispose = false, super.retry, }) : super( $allTransitiveDependencies: computeAllTransitiveDependencies( dependencies, ), from: null, argument: null, ); ``` -------------------------------- ### bool get isRefreshing Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/AsyncValueExtensions/isRefreshing.html A getter that returns true if the provider is being forced to recompute after an initial value or error has been emitted, typically via Ref.invalidate or Ref.refresh. ```APIDOC ## bool get isRefreshing ### Description Returns a boolean indicating if the provider is currently recomputing despite no dependency changes. This occurs when a provider is manually refreshed or invalidated after having already emitted a value or error. ### Usage - Returns `true` if the provider is refreshing. - Returns `false` if the provider is not refreshing (e.g., if it is reloading due to a dependency change, `isReloading` would be `true` instead). ``` -------------------------------- ### resume() Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/ProviderSubscription-class.html Resumes the subscription. ```APIDOC ## void resume() ### Description Resumes the subscription. ``` -------------------------------- ### bool get isPaused Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/Ref/isPaused.html Returns a boolean value 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 being disabled. ```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. ### Returns - **bool** - True if the Ref is paused, false otherwise. ``` -------------------------------- ### Implement create method Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/BlocProvider/create.html Overrides the create method to return a Bloc instance using the provided Ref. ```dart @override B create(Ref ref) => _create(ref); ``` -------------------------------- ### overrideWith(Create> create) Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/StreamProvider/overrideWith.html Overrides the provider with a new initialization function. This method disables the auto-scoping mechanism and is typically used for dependency injection in tests or environment-specific setups. ```APIDOC ## overrideWith(Create> create) ### Description Overrides the provider with a new initialization function. This will also disable the auto-scoping mechanism, meaning that if the overridden provider specified `dependencies`, it will have no effect. ### Parameters - **create** (Create>) - Required - A function that returns the new stream value for the provider. ### Usage Example ```dart final myService = Provider((ref) => MyService()); runApp( ProviderScope( overrides: [ myService.overrideWith((ref) { ref.watch('other'); return MyFakeService(); }), ], child: MyApp(), ), ); ``` ``` -------------------------------- ### Sorting a todo-list with watch Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/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) { ... }); }); ``` -------------------------------- ### Implementation of listen Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/ProviderContainer/listen.html The internal implementation of the listen method, including validation for the 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( ContainerNode(container: this), listener, weak: weak, onError: onError ?? defaultOnError, onDependencyMayHaveChanged: null, ); _handleFireImmediately(container, sub, fireImmediately: fireImmediately); sub.impl._listenedElement.addDependentSubscription(sub.impl); return sub; } ``` -------------------------------- ### Default implementation of runBuild Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/AsyncNotifier/runBuild.html The standard implementation that triggers the element's build process. ```dart @mustCallSuper @override WhenComplete runBuild() => requireElement().handleCreate(ref, build); ``` -------------------------------- ### Implement didCreateProviderContainer Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/ProviderObserver/didCreateProviderContainer.html Basic implementation of the didCreateProviderContainer method. ```dart void didCreateProviderContainer(ProviderContainer container) {} ``` -------------------------------- ### BlocObserver onCreate Implementation Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/BlocObserver/onCreate.html The default implementation of the onCreate method, which must be overridden and call super.onCreate. ```dart @protected @mustCallSuper void onCreate(BlocBase bloc) {} ``` -------------------------------- ### StateStreamable constructor Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/StateStreamable/StateStreamable.html Initializes a new instance of the StateStreamable class. ```APIDOC ## StateStreamable constructor ### Description Creates a new instance of the StateStreamable class to manage state streams. ### Signature StateStreamable() ``` -------------------------------- ### BlocProvider.when Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/BlocProvider-class.html Enables conditional rebuilds or listening based on state transitions. ```APIDOC ## BlocProvider.when((previous, current) => bool) ### Description Filters notifications so that the provider only triggers a rebuild or listener when the provided condition is met. ### Parameters - **condition** (Function) - Required - A predicate function taking (previous, current) states and returning a boolean. ``` -------------------------------- ### String toString() Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/BlocProvider/toString.html Returns a string representation of the BlocProvider object, including the name and argument if available. ```APIDOC ## String toString() ### Description Returns a string representation of this object. This method is typically overridden to provide useful information when inspecting the object, mainly for debugging or logging. ### Signature `String toString()` ### Returns - **String**: A string representation of the BlocProvider instance. ``` -------------------------------- ### MultiBlocObserver Constructor Implementation Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/MultiBlocObserver/MultiBlocObserver.html The constructor definition for the MultiBlocObserver class. ```dart const MultiBlocObserver({required this.observers}); ``` -------------------------------- ### Configure Auto Dispose Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/BlocProvider-class.html Shows how to define an auto-dispose BlocProvider to automatically clean up resources when no longer listened to. ```dart final counterProvider1 = BlocProvider.autoDispose((ref) => CounterCubit(0)); final counterProvider2 - AutoDisposeBlocProvider((ref) => CounterCubit(0)); ``` -------------------------------- ### Initialize BlocObserver Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/BlocObserver/BlocObserver.html The constructor for the BlocObserver interface. ```dart const BlocObserver(); ``` -------------------------------- ### Bloc(State initialState) Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/Bloc-class.html Constructor for the Bloc class, initializing it with an initial state. ```APIDOC ## Bloc(State initialState) ### Description Initializes a new Bloc instance with the provided initial state. ### Parameters - **initialState** (State) - Required - The starting state of the Bloc. ``` -------------------------------- ### Usage of allProviders with family filter Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/ProviderContainer/allProviders.html Demonstrates calling allProviders with a specific family before reading a provider from that family. ```dart final args = ref.container.allProviders(family: myFamily); ref.read(myFamily(0)); ``` -------------------------------- ### Cubit constructor Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/Cubit/Cubit.html Initializes a new Cubit instance with a required initial state. ```APIDOC ## Cubit constructor ### Description Creates a new instance of a Cubit. Every Cubit requires an initial state which will be the state of the Cubit before emit has been called. ### Signature Cubit(State initialState) ### Parameters - **initialState** (State) - Required - The initial state of the Cubit. ### Usage Example ```dart class CounterCubit extends Cubit { CounterCubit() : super(0); void increment() => emit(state + 1); } ``` ``` -------------------------------- ### listen implementation Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/Ref/listen.html The internal implementation of the listen method, which delegates to the underlying element subscription. ```dart @override 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(); final sub = _element.listen( provider, listener, weak: weak, onError: onError, fireImmediately: fireImmediately, ); return sub; } ``` -------------------------------- ### String toString() Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/Transition/toString.html Returns a string representation of the Transition object, including the currentState, event, and nextState. ```APIDOC ## String toString() ### Description Returns a string representation of the Transition object. This is primarily used for debugging and logging to inspect the object's state. ### Signature `String toString()` ### Returns - **String** - A string containing the current state, event, and next state of the transition. ``` -------------------------------- ### select Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/BlocProvider-class.html Partially listen to a provider by selecting a specific value. ```APIDOC ## select(OutT selector(InT value)) ### Description Partially listen to a provider. Available on ProviderListenable via the ProviderListenableSelect extension. ### Signature `ProviderListenable select(OutT selector(InT value))` ``` -------------------------------- ### String toString() Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/ProviderObserverContext/toString.html Returns a string representation of the ProviderObserverContext object, including the provider, container, and mutation details if available. ```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 identity. ``` -------------------------------- ### Initialize UnimplementedProviderError Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/UnimplementedProviderError/UnimplementedProviderError.html Constructor for creating an instance of UnimplementedProviderError with a specified name. ```dart UnimplementedProviderError(this.name); ``` -------------------------------- ### call(ArgT argument) Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/BlocProviderFamily-class.html Creates a specific BlocProvider instance from an external argument. ```APIDOC ## call(ArgT argument) ### Description Generates a BlocProvider instance based on the provided external argument. ### Parameters - **argument** (ArgT) - Required - The external value used to initialize the BlocProvider. ``` -------------------------------- ### Conceptual implementation of watch Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/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(); } ``` -------------------------------- ### StreamNotifierProvider.new Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/StreamNotifierProvider/StreamNotifierProvider.html Constructor for creating a new StreamNotifierProvider instance. ```APIDOC ## StreamNotifierProvider constructor ### Description A provider which creates and listens to a StreamNotifier. This is similar to FutureProvider but allows for performing side-effects. ### Signature StreamNotifierProvider, ValueT>( NotifierT _createNotifier(), { String? name, Iterable? dependencies, bool isAutoDispose = false, Retry? retry, }) ``` -------------------------------- ### Using when with a CounterCubit Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/ProviderListenableWhenable/when.html Demonstrates applying a filter to a provider to trigger updates based on specific state conditions. ```dart class CounterCubit extends Cubit { CounterCubit(super.state); void increment() => emit(state + 1); } final counterProvider = BlocProvider((ref) => CounterCubit(0)); Consumer( builder: (context, ref, __) { final _counter = ref.watch( counterProvider .when((prev, curr) => (curr + prev) % 5 == 0) .select((state) => 2 * state), ); return Text( '$_counter', style: Theme.of(context).textTheme.headline4, ); }, ) ``` -------------------------------- ### Implement a LoggingMixin using runBuild Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/AnyNotifier/runBuild.html Use this mixin to intercept the build process for logging purposes. Ensure super.runBuild() is called to maintain the notifier lifecycle. ```dart mixin LoggingMixin on AnyNotifier { @override void runBuild() { print('Will build $this'); super.runBuild(); print('Did build $this'); } } ``` -------------------------------- ### overrideWith Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/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 that creates the notifier. ### Parameters - **create** (NotifierT) - Required - The function to initialize the notifier. ``` -------------------------------- ### Initialize BlocBase Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/BlocBase/BlocBase.html The constructor initializes the state and notifies the bloc observer of the new instance creation. ```dart BlocBase(this._state) { // ignore: invalid_use_of_protected_member _blocObserver.onCreate(this); } ``` -------------------------------- ### when Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/AsyncResult-class.html Performs an action based on the state of the AsyncValue using 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 - Callback for data. - **error** (Function) - Required - Callback for error. - **loading** (Function) - Required - Callback for loading. ``` -------------------------------- ### AsyncNotifierProvider constructor Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/AsyncNotifierProvider/AsyncNotifierProvider.html Creates a provider that manages an AsyncNotifier instance. The notifier's ref and arguments are accessed directly within the AsyncNotifier class rather than through the provider function. ```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, }) ### Parameters - **_createNotifier** (Function) - Required - A function that returns an instance of the AsyncNotifier. - **name** (String) - Optional - An optional name for the provider. - **dependencies** (Iterable) - Optional - A list of providers that this provider depends on. - **isAutoDispose** (bool) - Optional - Whether the provider should automatically dispose when no longer listened to. Defaults to false. - **retry** (Retry) - Optional - Configuration for retry logic. ``` -------------------------------- ### Implementation of the on method Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/Bloc/on.html The internal implementation of the on method, showing how event handlers are registered and validated. ```dart void on( EventHandler handler, { EventTransformer? transformer, }) { // ignore: prefer_asserts_with_message assert(() { final handlerExists = _handlers.any((handler) => handler.type == E); if (handlerExists) { throw StateError( 'on<$E> was called multiple times. ' 'There should only be a single event handler per event type.', ); } _handlers.add(_Handler(isType: (dynamic e) => e is E, type: E)); return true; }()); final subscription = (transformer ?? _eventTransformer)( _eventController.stream.where((event) => event is E).cast(), (dynamic event) { void onEmit(State state) { if (super.isClosed) return; if (this.state == state && _emitted) return; onTransition( Transition( currentState: this.state, event: event as E, nextState: state, ), ); emit(state); } final emitter = _Emitter(onEmit); final controller = StreamController.broadcast( sync: true, onCancel: emitter.cancel, ); Future handleEvent() async { void tearDown() { emitter.complete(); _emitters.remove(emitter); if (!controller.isClosed) controller.close(); } try { _emitters.add(emitter); await handler(event as E, emitter); onDone(event); } catch (error, stackTrace) { onError(error, stackTrace); onDone(event as E, error, stackTrace); rethrow; } finally { tearDown(); } } handleEvent(); return controller.stream; }, ).listen(null); _subscriptions.add(subscription); } ``` -------------------------------- ### call Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/AutoDisposeBlocProviderFamilyBuilder-class.html Creates a group of providers that builds their value from an external parameter. ```APIDOC ### Method Signature `BlocProviderFamily call, S, ArgT>(B create(Ref ref, ArgT param), {String? name, Iterable? dependencies, Retry? retry})` ### Description Creates a family of auto-dispose BlocProviders that derive their value from an external parameter. ### Parameters - **create** (Function) - Required - A function that creates the Bloc or Cubit using the provided Ref and parameter. - **name** (String?) - Optional - An optional name for the provider. - **dependencies** (Iterable?) - Optional - A list of dependencies for the provider. - **retry** (Retry?) - Optional - Retry configuration for the provider. ``` -------------------------------- ### BlocProvider Constructor Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/BlocProvider-class.html Creates a new BlocProvider instance with a factory function and optional configuration parameters. ```APIDOC ## BlocProvider(B _create(Ref ref), {String? name, Iterable? dependencies, bool isAutoDispose = false, Retry? retry}) ### Description Initializes a new BlocProvider that manages a Bloc instance created by the provided factory function. ### Parameters - **_create** (Function) - Required - A function that returns the Bloc instance. - **name** (String?) - Optional - A custom label for the provider. - **dependencies** (Iterable?) - Optional - List of providers this provider depends on. - **isAutoDispose** (bool) - Optional - Whether the state should be disposed when no longer listened to. - **retry** (Retry?) - Optional - The retry strategy for the provider. ``` -------------------------------- ### Initialize ProviderObserver Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/ProviderObserver/ProviderObserver.html The constructor for the ProviderObserver class. ```dart const ProviderObserver(); ``` -------------------------------- ### Transition Constructor Definition Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/Transition/Transition.html Defines the required parameters for creating a new Transition instance. ```dart const Transition({ 1. required State currentState, 2. required Event event, 3. required State nextState, }) ``` -------------------------------- ### Using emit in a Bloc EventHandler Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/Bloc/emit.html Demonstrates the standard usage of the emit function within a Bloc's event handler to transition to a new state. ```dart class MyBloc extends Bloc { MyBloc() : super(MyInitialState()) { on((event, emit) { // use `emit` to update the state. emit(MyOtherState()); }); } } ``` -------------------------------- ### bool exists(ProviderBase provider) Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/ProviderContainer/exists.html Determines whether a provider is initialized or not. Returns true if the provider is initialized, false otherwise. ```APIDOC ## bool exists(ProviderBase provider) ### Description Determines whether a provider is initialized or not. Writing logic that conditionally depends on the existence of a provider is generally unsafe and should be avoided, but it can be useful for avoiding redundant network requests. ### Parameters - **provider** (ProviderBase) - Required - The provider instance to check for initialization. ### Returns - **bool** - Returns true if the provider is initialized, false otherwise. ``` -------------------------------- ### AsyncNotifierProvider Implementation Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/AsyncNotifierProvider/AsyncNotifierProvider.html The internal implementation of the AsyncNotifierProvider constructor. ```dart AsyncNotifierProvider( this._createNotifier, { super.name, super.dependencies, super.isAutoDispose = false, super.retry, }) : super( $allTransitiveDependencies: computeAllTransitiveDependencies( dependencies, ), from: null, argument: null, ); ``` -------------------------------- ### Define a FutureProvider for configuration Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/FutureProvider/FutureProvider.html Expose a configuration object by reading a JSON file asynchronously using the provider. ```dart final configProvider = FutureProvider((ref) async { final content = json.decode( await rootBundle.loadString('assets/configurations.json'), ) as Map; return Configuration.fromJson(content); }); ``` -------------------------------- ### when Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/Provider-class.html Provides a filtering mechanism for listening to provider changes, similar to BlocListener or BlocBuilder. ```APIDOC ### Method `when(ListenWhen filter)` ### Description Allows the user to define a filter condition for when the provider should trigger updates, similar to the buildWhen or listenWhen patterns in Bloc. ``` -------------------------------- ### BlocBase Methods Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/BlocBase-class.html Core methods available on BlocBase instances for managing state and lifecycle. ```APIDOC ## void addError(Object error, [StackTrace? stackTrace]) ### Description Reports an error which triggers onError with an optional StackTrace. ## Future close() ### Description Closes the instance. This method should be called when the instance is no longer needed. Once close is called, the instance can no longer be used. ## void emit(State state) ### Description Updates the state to the provided state. emit does nothing if the state being emitted is equal to the current state. ## void onChange(Change change) ### Description Called whenever a change occurs with the given change. A change occurs when a new state is emitted. onChange is called before the state of the cubit is updated. ## void onError(Object error, StackTrace stackTrace) ### Description Called whenever an error occurs and notifies BlocObserver.onError. ``` -------------------------------- ### runBuild Source: https://pub.dev/documentation/riverbloc/latest/riverbloc/AnyNotifier-class.html Executes the build logic for the notifier, which can be overridden to perform actions before or after the build process. ```APIDOC ## runBuild() -> WhenComplete? ### Description Executes the Notifier.build method. This can be overridden to inject custom logic before or after the build execution. ```