import 'package:flutter/material.dart';
class LoginFormScreen extends StatefulWidget {
@override
State<LoginFormScreen> createState() => _LoginFormScreenState();
}
class _LoginFormScreenState extends State<LoginFormScreen> {
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Simple Login Form')),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
children: [
TextFormField(
decoration: InputDecoration(labelText: 'Email'),
keyboardType: TextInputType.emailAddress,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your email';
}
if (!value.contains('@')) {
return 'Enter a valid email';
}
return null;
},
),
TextFormField(
decoration: InputDecoration(labelText: 'Password'),
obscureText: true,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your password';
}
if (value.length < 6) {
return 'Password must be at least 6 characters';
}
return null;
},
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
if (_formKey.currentState?.validate() ?? false) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Login Successful!')),
);
}
},
child: Text('Login'),
),
],
),
),
),
);
}
}
This screen uses a Form widget with a GlobalKey to manage the form state. The TextFormField widgets each have a validator function that checks the input. The email field checks if the input is not empty and contains an '@' symbol. The password field checks if the input is not empty and has at least 6 characters.
When the Login button is pressed, the form is validated by calling _formKey.currentState?.validate(). If all validators return null (meaning valid), a SnackBar appears with a success message. This approach keeps validation logic clean and user feedback immediate.