Using Riverpod In the below code. I don't want the textField value to be updated through rebuilds Just I want to get the value from the state at the first time, and I need to keep listening to the state to update other things.
If the user updated the field then the widget rebuilt, I need to keep the user's value without refresh.
class Example extends ConsumerWidget {
const Example({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
final state = ref.watch(myStateProvider);
return TextFormField(
controller: TextEditingController(text: state.firstName.value),
textInputAction: TextInputAction.next,
decoration: InputDecoration(
labelText: 'First Name', errorText: state.firstName.errorMessage),
);
}
}
Without using onChange
CodePudding user response:
You can use a ConsumerStatefulWidget
:
class Example extends ConsumerStatefulWidget {
const Example({
Key? key,
}) : super(key: key);
@override
_ExampleState createState() => _ExampleState();
}
class _ExampleState extends ConsumerState<Example> {
final _textEditingController = TextEditingController();
@override
void initState() {
super.initState()
_textEditingController.text = ref.read(myStateProvider).firstName.value;
}
@override
void dispose() {
_textEditingController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context, WidgetRef ref) {
final state = ref.watch(myStateProvider);
return TextFormField(
controller: _textEditingController,
textInputAction: TextInputAction.next,
decoration: InputDecoration(
labelText: 'First Name', errorText: state.firstName.errorMessage),
);
}
}