I use widget StatefulWidget and _inputFiled
I’ve created a model class
class Profile {
String? email;
String? username;
String? password;
Profile({
this.email,
this.username,
this.password,
});
}
And using like
class _RegisterScreenState extends State<RegisterScreen> {
final formKey = GlobalKey<FormState>();
Profile profile = Profile();
@override
Widget build(BuildContext context) {
return Form(
child: Scaffold(
body: Container(
margin: EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
// _header(context),
_inputField(context),
// _forgotPassword(context),
],
),
),
),
);
}
_inputField(context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextFormField(
keyboardType: TextInputType.emailAddress,
onSaved: (String? email) {
formKey.currentState?.save();
profile.email = email!;
},
),
SizedBox(height: 10),
TextFormField(
onSaved: (String? username) {
formKey.currentState?.save();
profile.username = username!;
},
),
SizedBox(height: 10),
TextFormField(
onSaved: (String? password) {
profile.password = password!;
},
),
SizedBox(height: 10),
ElevatedButton(
onPressed: () {
formKey.currentState?.save(); // Save the entire form
print(
"email =${profile.email} username =${profile.username} password =${profile.password}");
Navigator.push(context, MaterialPageRoute(builder: ((context) {
return LoginScreen();
})));
},
child: Text(
"Register",
),
)
],
);
}
Terminal say : email =null username =null password =null
3
Answers
The form key hasn’t been used.
You need put your Global key in your form:
And the formKey.currentState?.save() only on
it is not needed in onSave methods as it will be executed first on button onPressed
It is becauae you made them null able and if you dont initialize them the first value will be null.