Minimum reproducible code:
final GlobalKey<FormState> _globalKey = GlobalKey();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Form(
key: _globalKey,
child: TextFormField(onSaved: (String? string) {},
),
ElevatedButton(
onPressed: () => _globalKey.currentState!.save(),
child: Text('Save'),
),
],
),
);
}
Even if I don't enter anything (or bring this field in focus), clicking the Save
button still gives me a non-null String
. So, why does the onSaved
requires a nullable String?
in its parameter list i.e. why can't I do the following as onSaved
always seems to have a non nullable value.
onSaved: (String string) {}, // Error
CodePudding user response:
I think it's because you can leave the field empty. If the input type is for example numbers you can't convert an empty field to int.
CodePudding user response:
onSaved
is defined as FormFieldSetter<String>? onSaved,
And FormFieldSetter
is
typedef FormFieldSetter<T> = void Function(T? newValue);
So it expects nullable datatype on callback
solution is
onSaved: (String? string) {},