overrideWithValue method

  1. @override
Override overrideWithValue(
  1. AsyncValue<T> value
)
inherited

Overrides the behavior of a provider with a value.

Some common use-cases are:

  • testing, by replacing a service with a fake implementation, or to reach a very specific state easily.
  • multiple environments, by changing the implementation of a class based on the platform or other parameters.

This function should be used in combination with ProviderScope.overrides or ProviderContainer.overrides:

final myService = Provider((ref) => MyService());

runApp(
  ProviderScope(
    overrides: [
      myService.overrideWithProvider(
        // Replace the implementation of MyService with a fake implementation
        Provider((ref) => MyFakeService())
      ),
    ],
    child: MyApp(),
  ),
);

Implementation

@override
Override overrideWithValue(AsyncValue<T> value) {
  return ProviderOverride(
    ValueProvider<Future<T>, AsyncValue<T>>((ref) {
      final completer = Completer<T>()
        // Catch the error so that it isn't pushed to the zone. This is safe since FutureProvider catches errors for us
        // ignore: avoid_types_on_closure_parameters
        ..future.then((_) {}, onError: (Object _) {});
      ref.onChange = (newValue) {
        if (completer.isCompleted) {
          ref.markMustRecomputeState();
        } else {
          newValue.when(
            data: completer.complete,
            loading: () {},
            error: completer.completeError,
          );
        }
      };
      ref.onChange!(value);
      return completer.future;
    }, value),
    this,
  );
}