overrideWith method

Override overrideWith(
  1. NotifierT create(
    1. AutoDisposeChangeNotifierProviderRef<NotifierT> ref,
    2. Arg arg
    )
)

Override 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.

The override must not specify a dependencies.

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: [
      // Replace the implementation of the provider with a different one
      myService.overrideWithProvider((ref) {
        ref.watch('other');
        return MyFakeService(),
      })),
    ],
    child: MyApp(),
  ),
);

Implementation

Override overrideWith(
  NotifierT Function(
    // ignore: deprecated_member_use_from_same_package
    AutoDisposeChangeNotifierProviderRef<NotifierT> ref,
    Arg arg,
  ) create,
) {
  return FamilyOverrideImpl<NotifierT, Arg,
      AutoDisposeChangeNotifierProvider<NotifierT>>(
    this,
    (arg) => AutoDisposeChangeNotifierProvider<NotifierT>.internal(
      (ref) => create(ref, arg),
      from: from,
      argument: arg,
      name: null,
      dependencies: null,
      allTransitiveDependencies: null,
      debugGetCreateSourceHash: null,
    ),
  );
}