我有一个按钮,使用一个计数器Provider 与Riverpod,我想添加一个本地状态isLoading
到按钮.
虽然我可以在build
方法中完成这一切,但我想知道是否有一种方法可以将状态提升到实例级,以便Btn
类中的其他方法也可以访问此状态,例如,使onPressed
函数进入另一个方法.
build
里面的代码:
class Btn extends HookConsumerWidget {
const Btn({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final isLoading = useState(false);
final counter = ref.watch(counterProvider);
final counterNotifier = ref.read(counterProvider.notifier);
useEffect(() {
if (isLoading.value) {
Future.delayed(const Duration(seconds: 1), () {
isLoading.value = false;
counterNotifier.reset();
});
}
return null;
}, [isLoading.value]);
return ElevatedButton.icon(
onPressed: () => isLoading.value = true : null,
icon: isLoading.value ? const CircularProgressIndicator() : Container(),
label:Text(isLoading.value ? "Loading" : "$counter"),
);
}
}
我想把它变成:
class Btn extends HookConsumerWidget {
const Btn({super.key});
// declare isLoading
void onPressed() {
isLoading.value = true;
}
@override
Widget build(BuildContext context, WidgetRef ref) {
final counter = ref.watch(counterProvider);
final counterNotifier = ref.read(counterProvider.notifier);
useEffect(() {
if (isLoading.value) {
Future.delayed(const Duration(seconds: 1), () {
isLoading.value = false;
counterNotifier.reset();
});
}
return null;
}, [isLoading.value]);
return ElevatedButton.icon(
onPressed: onPressed,
icon: isLoading.value ? const CircularProgressIndicator() : Container(),
label: Text(isLoading.value ? "Loading" : "$counter"),
);
}
}