I want to show error under field if there is some error on submit and clear the error when typing again. This is what I have done so far. It works first time but on further attempts to submit it keeps showing error under field since the controller is in error state. I feel like I’m missing a core point of doing this declaratively. I keep thinking imperatively. Is there a neat solution to this, Thanks.
// submit_controller.dart
class SubmitController extends AsyncNotifier<void> {
@override
FutureOr<void> build() {}
Future<void> submit() async {
state = const AsyncValue.loading();
try {
await Future.delayed(const Duration(seconds: 3));
throw Exception('Invalid OTP');
} catch (error, st) {
state = AsyncError(error, st);
}
}
}
// main.dart
class HomePage extends ConsumerStatefulWidget {
...
@override
Widget build(BuildContext context) {
final submit = ref.watch(submitControllerProvider);
ref.listen(submitControllerProvider, (_, state) {
final error = (state.error as Exception).toString();
if (error == 'Exception: Invalid OTP') {
isError = true;
controller.clear();
}
});
return Scaffold(
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
enabled: !submit.isLoading,
controller: controller,
onChanged: (value) => setState(() {
isError = false;
}),
),
isError
? const Text(
'Invalid OTP',
style: TextStyle(color: Colors.red),
)
: const SizedBox.shrink(),
TextButton(
onPressed: () {
ref.read(submitControllerProvider.notifier).submit();
},
child: const Text('Submit')),
],
),
),
);
}
}