'in TexformField , Null check operator used on a null value flutter
[my simple program][1] class _MyHomePageState extends
State<MyHomePage> {
String? username;
@override
Widget build(BuildContext context) {
GlobalKey<FormState> formstate =
new GlobalKey<FormState>();
send() {
var _formdate = formstate.currentState;
if (_formdate!.validate()) {
_formdate.save();
print('valid');
print('$username');
} else {
(print('not valid'));
print('$username');
}
}
return MaterialApp(
home: Scaffold(
appBar: AppBar(
backgroundColor: Colors.black,
),
body: Form(
autovalidateMode: AutovalidateMode.always,
key: formstate,
child: Column(
children: [
TextFormField(onSaved: (text) {
username = text;
}, validator: (text) {
if (text!.length <= 4) {
return " text can not be equal or less than 4 characters";
}
if (text.length > 10) {
return "maximum number is 10 characters";
}
return "you are correct";
}),
RaisedButton(
onPressed: () {
send();
},
child: const Text('send'),
),
],
),
),
),
);
}
}
- after running , when i enter valid name and press send, it also gives null and not valid at console, and when remove null check(!) it gives error, don't know how to solve.
- tried to use currentstate.validate and same issue 😖
Solution 1:[1]
try
String username = "";
and if this does not work provide more detail on what are you trying to do.
Solution 2:[2]
Instead of:
return "you are correct";
write:
return null;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ravipatel0508 |
| Solution 2 | M Karimi |
