I'm trying to set the value of a field programmatically using flutter_form_builder and it doesn't seem to be in the docs.
the controller:
class LoggedOutNicknameController extends GetxController {
AnimationController animateController;
bool formValid;
final GlobalKey<FormBuilderState> formKey = GlobalKey<FormBuilderState>();
@override
void onInit() {}
@override
void onReady() {
final box = GetStorage();
box.erase();
if (box.read<dynamic>('nickname') != null &&
box.read<dynamic>('nickname') != '') {
print(box.read<dynamic>('nickname')); // prints the value eg 'James'
final fff = box.read<String>('nickname');
formKey.currentState.setAttributeValue('nickname', fff);
}
}
@override
void onClose() {}
void onFormChange() {
formValid = formKey.currentState.validate();
}
}
After that code there supposedly sets the value, the value does not display in my text input.
The view:
Expanded(
flex: 4,
child: FormBuilder(
key: controller.formKey,
autovalidateMode: AutovalidateMode.onUserInteraction,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
VpSubtitle1(
context,
'So nice to meet you! What do your friends call you?',
TextAlign.center),
FormBuilderTextField(
attribute: 'nickname',
textAlign: TextAlign.center,
decoration:
const InputDecoration(hintText: 'Nickname...'),
validators: [FormBuilderValidators.required()],
)
]))),
Why does the value not show up in the text input?
It is very simple and clarified in the official docs,
You can either change the value of one field at a time like so:
_formKey.currentState.fields['color_picker'].didChange(Colors.black);
Or multiple fields value like so:
_formKey.currentState.patchValue({
'age': '50',
'slider': 6.7,
'filter_chip': ['Test 1'],
'choice_chip': 'Test 2',
'rate': 4,
'chips_test': [
Contact('Andrew', 'stock@man.com', 'https://d2gg9evh47fn9z.cloudfront.net/800px_COLOURBOX4057996.jpg'),
],
});
Refer to this part in the docs: flutter_form_builder: Programmatically changing field value