Using Forms In Flutter

aayush bajaj
2 min readMay 26, 2021

Well as a beginner in Flutter i am confused a lot as with each new update to the framework so many things change and its hard to keep up with all of it.

So i decided to help others save a little time where i spent hours figuring things out.

Here in this article we will be looking into how to use forms to build a simple login page UI. The documentation on Forms for flutter is not good according to me so here i will provide the whole code how to implement a simple login page and the same approach can be used for the signup page.

First we will Declare a Global Key for the form. and we will declare the variables we want to get from the users.


class LoginScreen extends StatefulWidget {

@override
_LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
final _formkey = GlobalKey();
late String _email;
late String _password;
}

Next we will jump to the body part and declare a form and two textform fields like this.

Form(
//the key we declared on the top
key: _formkey,
child: Column(
children: <Widget>[
TextFormField(
//this defines the type of text we want the user to enter
decoration: InputDecoration(labelText: "Email"),
keyboardType: TextInputType.emailAddress,
onChanged: (value) {
setState(() {
_email = value;
});
},
//this validates the eneterd values
validator: (value) {
if (value == null || !value.contains('@')) {
return "Invalid Emial!";
}
}
,
),
TextFormField(
decoration: InputDecoration(labelText: "Password"),
keyboardType: TextInputType.visiblePassword,
obscureText: true,
onChanged: (value) {
setState(() {
_password = value;
});
},
validator: (value) {
if (value == null || value.length < 7) {
return "Invalid Password";
}
}
,
),
ElevatedButton(
onPressed: () {
if (_formkey.currentState!.validate()) {
print(_email);
print(_password);
}
},
child: Text('Login'),
)
]
,
),
)

In the last step we just have to pass on the data to the auth controller whenever the elevated button is pressed as we have already stored the values of email and password in the variables.

so this is a small code for your very basic login page u just need to add the firebase code and you are off to the races.

--

--