Last active
January 14, 2025 21:12
-
-
Save jjbubudi/5ff7a50df9a2bc3919888981a7924561 to your computer and use it in GitHub Desktop.
Riverpod Mutation Provider
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter_riverpod/flutter_riverpod.dart'; | |
class MutationProvider { | |
static AutoDisposeNotifierProvider<MutationNotifier<Arg, ReturnType>, | |
AsyncValue<ReturnType?>> autoDispose<Arg, ReturnType>({ | |
required Future<ReturnType> Function(Ref, Arg) mutationFn, | |
}) { | |
return NotifierProvider.autoDispose( | |
() => MutationNotifier( | |
mutationFn: mutationFn, | |
), | |
); | |
} | |
} | |
class MutationNotifier<Arg, ReturnType> | |
extends AutoDisposeNotifier<AsyncValue<ReturnType?>> { | |
MutationNotifier({ | |
required Future<ReturnType> Function(Ref ref, Arg arg) mutationFn, | |
}) : _mutationFn = mutationFn; | |
final Future<ReturnType> Function(Ref ref, Arg arg) _mutationFn; | |
@override | |
AsyncValue<ReturnType?> build() { | |
return const AsyncValue.data(null); | |
} | |
Future<AsyncValue<ReturnType>> mutate(Arg arg) async { | |
state = AsyncValue.loading(); | |
state = await AsyncValue.guard(() async { | |
return await _mutationFn(ref, arg); | |
}); | |
return state as AsyncValue<ReturnType>; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment