best practice for updating state in AsyncNotifier class #2423
-
Hi!
Future<void> updateState(
dynamic value,
) async {
state.when(
data: (previousState) {
return state = AsyncValue.data(
previousState.copyWith(sampleField: value),
);
},
error: (error, stackTrace) => AsyncValue.error(error, stackTrace),
loading: () => const AsyncValue.loading(),
);
}
Future<void> updateState(
dynamic value,
) async {
// I do not like this null check.
final previousState = state.asData!.value;
final newState = previousState.copyWith(sampleFiled: value);
state = const AsyncValue.loading();
state = await AsyncValue.guard(() async {
return newModel;
});
}
Future<void> updateState(dynamic value) async {
await update(
(previousState) {
final newState = previousState.copyWith(sampleField: value);
return newState;
},
);
} Thank you. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
Note: Both |
Beta Was this translation helpful? Give feedback.
-
May be a little late here .. But I just want to know how I can have different states for different API calls inside a single AsyncNotifier provider ? |
Beta Was this translation helpful? Give feedback.
state.when
: can be used to update state only if current state is something (i.e you can ignore updating if current state is loading/error). Btw, In your sample loading/error flags do nothing beside just returning current error/loading.update
: close tostate.when
but if current state isloading
, the update will be awaited and called ifdata
is emitted later. If current state is error, the callback will not be invoked (onError can be used to handle if current state is error).Note: Both
state.when
&update
don't try/catch errors and typically used when your update is sync. If your update is async and does throw errors, that's whenAsyncGuard
is preferred.