【发布时间】:2021-07-24 06:03:02
【问题描述】:
我有一个 isLoading StateNotifierProvider 来在我的按钮被点击时添加一个加载指示器,直到异步方法完成。
但是,当我同时看到两个按钮时,当只点击一个按钮时,它们都会显示指示器。
如何将 StateNotifierProvider 限定为每个按钮一个实例,而不是所有按钮一个实例?
按钮:
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),
);
}
}
提供者:
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;
}
}
}
【问题讨论】: