I am reading Chapter 6 of the Flutter Cookbook – Second Edition by Simone Alessandria, and I am trying to implement email validation in the login_screen.dart file as demonstrated in the book. However, the email validation does not seem to work as expected.
Here is my code:
import 'package:flutter/material.dart';
import 'stopwatch.dart';
class LoginScreen extends StatefulWidget {
static const route = '/login';
const LoginScreen({super.key});
@override
State<LoginScreen> createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
final _nameController = TextEditingController();
final _emailController = TextEditingController();
final _formKey = GlobalKey<FormState>();
bool loggedIn = false;
String name = '';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Login'),
),
body: Center(
child: loggedIn ? _buildSuccess() : _buildLoginForm(),
),
);
@override
void dispose() {
_emailController.dispose();
_nameController.dispose();
super.dispose();
}
}
Widget _buildSuccess() {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.check, color: Colors.orangeAccent),
Text('Hi $name')
],
);
}
Widget _buildLoginForm() {
return Form(
key: _formKey,
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextFormField(
controller: _nameController,
decoration: const InputDecoration(labelText: 'Runner'),
validator: (text) =>
text!.isEmpty ? 'Enter the runner's name.' : null,
),
TextFormField(
controller: _emailController,
keyboardType: TextInputType.emailAddress,
decoration: const InputDecoration(labelText: 'Email'),
validator: (text) {
if (text!.isEmpty) {
return 'Enter the runner's email.';
}
final regex = RegExp('[^@]+@[^.]+..+');
if (!regex.hasMatch(text)) {
return 'Enter a valid email';
}
return null;
},
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: _validate,
child: const Text('Continue'),
),
],
)));
}
void _validate() {
final form = _formKey.currentState;
if (form?.validate() ?? false) {
return;
}
setState(() {
loggedIn = true;
name = _nameController.text;
});
}
}
The email validation logic is supposed to ensure that the email input matches the regex pattern [^@]+@[^.]+..+. However, when I run the app, even invalid email addresses are being accepted.
The full code can be found on the author’s GitHub
Could someone help me identify why the email validation is not working as expected? Any guidance on what might be wrong or how to fix it would be greatly appreciated.