I'm getting this compiler error in the following provider code:
The argument type 'AsyncCatNotifier Function(dynamic)' can't be assigned to the parameter type 'AsyncCatNotifier Function()'.dartargument_type_not_assignable (new) AsyncCatNotifier AsyncCatNotifier({required NetworkService networkService}) package:coolcatsclient/providers/provider_async_cat.dart
class AsyncCatNotifier extends AsyncNotifier<AsyncValue<Cat?>> {
final NetworkService networkService;
AsyncCatNotifier({required this.networkService}) : super();
Future<void> fetchCat(int catId) async {
try {
final cat = await networkService.fetchCat(catId);
state = AsyncData(AsyncData(cat)); // Update state with fetched cat
} catch (error, stackTrace) {
state = AsyncError(error, stackTrace); // Handle errors
}
}
@override
FutureOr<AsyncValue<Cat?>> build() {
return const AsyncLoading(); // Default initial state while loading
}
}
final asyncCatProvider = AsyncNotifierProvider.autoDispose<AsyncCatNotifier, AsyncValue<Cat?>>(
// compiler error happens here
(ref) => AsyncCatNotifier(networkService: ref.read(networkServiceProvider)),
);
There are a few things to keep in mind when using
AsyncNotifier.buildmethod. Either by usingRef.watchor from thebuildparameters (family).AsyncNotifierto be auto disposed, extendsAutoDisposeAsyncNotifier, there are alsoFamilyAsyncNotifierandAutoDisposeFamilyAsyncNotifier. Consider using code generation to avoid dealing with the type ofNotifier/Provider.AsyncNotifier's type argument withAsyncValue. The state of anAsyncNotifierisAsyncValue<T>whereTis the type argument of theAsyncNotifier. For instance, yourAsyncCatNotifiershould probably extendsAutoDisposeAsyncNotifier<Cat?>.AsyncLoading()inside theAsyncNotifier'sbuildmethod is undesirable most of the time. Instead, initialise theAsyncNotifierright a way.AsyncNotifier, consider converting it to aFutureProvider.Below is how I would implement it:
Below is a
Dogversion with code generation. Notice how it let youNotifier/Provider's type, you do not have to choose betweenAsyncNotifier/AutoDisposeAsyncNotifier/FamilyAsyncNotifier/AutoDisposeFamilyAsyncNotifier