I have an isLoading
StateNotifierProvider
to add a loading indicator to my buttons when they are tapped until the async method has completed.
However, when I have two buttons visible at once, they both show the indicator when only one was tapped.
How do I scope the StateNotifierProvider to one instance per button instead of one instance for all buttons?
Button:
class AsyncSubmitButton extends ConsumerWidget {
AsyncSubmitButton(
{required this.text,
required this.onPressed})
: super(key: key);
final String text;
final Future<void> Function() onPressed;
@override
Widget build(BuildContext context, ScopedReader watch) {
final isLoading = watch(isLoadingProvider);
final form = ReactiveForm.of(context)!;
return ElevatedButton(
onPressed: form.invalid
? null
: () => context.read(isLoadingProvider.notifier).pressed(onPressed),
child: isLoading
? const CircularProgressIndicator()
: Text(text),
);
}
}
Provider:
final isLoadingProvider =
StateNotifierProvider<AsyncSubmitButtonLoadingStateNotifier, bool>((ref) {
return AsyncSubmitButtonLoadingStateNotifier(isLoading: false);
});
class AsyncSubmitButtonLoadingStateNotifier extends StateNotifier<bool> {
AsyncSubmitButtonLoadingStateNotifier({required bool isLoading})
: super(isLoading);
dynamic pressed(Future<void> Function() onPressedFunction) async {
state = true;
try {
await onPressedFunction();
} catch (error) {
state = false;
} finally {
state = false;
}
}
}