Introduction
A login screen is one of the most fundamental UI components in any mobile application â it's often the first thing your users see, and it sets the tone for the entire app experience. Building a clean, functional, and secure login screen with Flutter is an excellent exercise that teaches you form validation, state management, navigation, and API integration all at once. In this step-by-step tutorial, the GSoft Technologies team walks you through building a professional Flutter login screen from scratch, complete with email/password validation, loading states, and error handling.
What is Flutter Form Management?
Flutter provides a powerful Form widget system that combines TextFormField widgets with a GlobalKey<FormState> controller. This system handles validation, saving form data, and resetting fields in a clean, declarative way. For a login screen, we'll combine Flutter's form system with state management to handle authentication flow â including loading states, API calls, and error display. This tutorial assumes you have Fluttave Flutter installed and understand the basics of widgets and Dart.
Key Features / What We Will Build
By the end of this tutorial, your Flutter login screen will include:
- Email and password text fields with real-time validation and appropriate keyboard types.
- Password visibility toggle â a show/hide eye icon in the password field.
- Form validation â checks for empty fields, valid email format, and minimum password length before submission.
- Loading indicator â disables the button and shows a spinner while the login API call is in progress.
- Error display â shows a SnackBar or inline error when authentication fails.
- Clean, modern UI â using Material 3 design with custom colors and typography.
Step-by-Step: Building the Flutter Login Screen
Let's build this login screen step by step. Create a new file at lib/screens/login_screen.dart and follow along:
import 'package:flutter/material.dart';class LoginScreen extends StatefulWidget { const LoginScreen({super.key}); @override State<LoginScreen> createState() => _LoginScreenState();}class _LoginScreenState extends State<LoginScreen> { final _formKey = GlobalKey<FormState>(); final _emailController = TextEditingController(); final _passwordController = TextEditingController(); bool _isLoading = false; bool _obscurePassword = true; String? _errorMessage;:#e5e5e5;padding:20px;border-radius:8px;overflow-x:auto;white-space:pre;font-family:'Courier New',Courier,monospace;font-size:14px;line-height:1.6;"> @override void dispose() { _emailController.dispose(); _passwordController.dispose(); super.dispose(); } Future<void> _handleLogin() async { // Clear previous error setState(() => _errorMessage = null); // Validate form fields if (!_formKey.currentState!.validate()) return; setState(() => _isLoading = true); try { // Simulate an API call â replace with your real auth service await Future.delayed(const Duration(seconds: 2)); // Example: await AuthService.login( // email: _emailController.text.trim(), // password: _passwordController.text, // ); // On success, navigate to home if (mounted) { Navigator.pushReplacementNamed(context, '/home'); } } catch (e) { setState(() { _errorMessage = 'Invalid email or password. Please try again.'; }); } finally { if (mounted) setState(() => _isLoading = false); } } your real auth service await Future.delayed(const Duration(seconds: 2)); // Example: await AuthService.login( // email: _emailController.text.trim(), // password: _passwordController.text, // ); // On success, navigate to home if (mounted) { Navigator.pushReplacementNamed(context, '/home'); } } catch (e) { setState(() { _errorMessage = 'Invalid email or password. Please try again.'; }); } finally { if (mounted) setState(() => _isLoading = false); } } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: const Color(0xFFF8F9FA), body: SafeArea( child: Center( child: SingleChildScrollView( padding: const EdgeInsets.symmetric(horizontal: 28.0), child: Form( key: _formKey, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ const SizedBox(height: 40), const Icon(Icons.lock_outline, size: 64, color: Color(0xFF00E676)),ns.lock_outline, size: 64, color: Color(0xFF00E676)), const SizedBox(height: 16), const Text( 'Welcome Back', textAlign: TextAlign.center, style: TextStyle(fontSize: 28, fontWeight: FontWeight.bold), ), const SizedBox(height: 8), const Text( 'Sign in to your account', textAlign: TextAlign.center, style: TextStyle(fontSize: 16, color: Colors.grey), ), const SizedBox(height: 40), TextFormField( controller: _emailController, keyboardType: TextInputType.emailAddress, textInputAction: TextInputAction.next, decoration: InputDecoration( labelText: 'Email Address', prefixIcon: const Icon(Icons.email_outlined), border: OutlineInputBorder( borderRadius: BorderRadius.circular(12), ), filled: true, fillColor: Colors.white, ), validator: (value) { if (value == null || value.trim().isEmpty) { return 'Please enter your email address'; } final emailRegex = RegExp(r'^[^@]+@[^@]+\.[^@]+'); if (!emailRegex.hasMatch(value.trim())) {rRadius.circular(12), ), filled: true, fillColor: Colors.white, ), 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; }, ), // Error Message if (_errorMessage != null) ..[ const SizedBox(height: 12), Container( padding: const EdgeInsets.all(12), decoration: BoxDecoration( color: Colors.red.shade50, borderRadius: BorderRadius.circular(8), border: Border.all(color: Colors.red.shade200), ), child: Text( _errorMessage!, style: TextStyle(color: Colors.red.shade700, fontSize: 14), ), ), ],Icon: const Icon(Icons.lock_outline), suffixIcon: IconButton( icon: Icon( _obscurePassword ? Icons.visibility_outlined : Icons.visibility_off_outlined, ), onPressed: () { setState(() => _obscurePassword = !_obscurePassword); }, ), border: OutlineInputBorder( borderRadius: BorderRadius.circular(12), ), filled: true, fillColor: Colors.white, ), 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; }, ), // Error Message if (_errorMessage != null) ..[ const SizedBox(height: 12), Container( const SizedBox(height: 24), // Login Button SizedBox( height: 52, child: ElevatedButton( onPressed: _isLoading ? null : _handleLogin, style: ElevatedButton.styleFrom( backgroundColor: const Color(0xFF00E676), foregroundColor: Colors.black, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12), ), ), child: _isLoading ? const SizedBox( width: 24, height: 24, child: CircularProgressIndicator( strokeWidth: 2.5, color: Colors.black54, ), ) : const Text( 'Sign In', style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), ), ), const SizedBox(height: 40), ], ), ), ), ), ), ); }} foregroundColor: Colors.black, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12), ), ), child: _isLoading ? const SizedBox( width: 24, height: 24, child: CircularProgressIndicator( strokeWidth: 2.5, color: Colors.black54, ), ) : const Text( 'Sign In', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold), ), ), ), const SizedBox(height: 40), ], ), ), ), ), ), ); }}
Best Practices
When building authentication screens in Flutter, keep these security and UX best practices in mind:
- Never store passwords in plain text: Always transmit credentials over HTTPS and let your backend handle hashing. Never log or store raw passwords on the device.
- When building authentication screens in Flutter, keep these security and UX best practices in mind:
- Never store passwords in plain text: Always transmit credentials over HTTPS and let your backend handle hashing. Never log or store raw passwords on the device.
- Use
dispose()for controllers: Always disposeTextEditingControllerinstances in the widget'sdisposemethod to prevent memory leaks. - Check
mountedbefore calling setState: After async operations, always checkif (mounted)before updating state to avoid calling setState on a disposed widget. - Provide clear validation messages: Tell users exactly what's wrong with their input. Vague messages like "Invalid input" frustrate users and increase support requests.
- Implement rate limiting: Work with your backend to limit failed login attempts and protect against brute-force attacks.
- Support biometric authentication: Consider adding fingerprint/Face ID login using the
locfingerprint/Face ID login using thelocal_authpackage for a seamless UX on repeat visits. Real-World Use Cases at GSoft TechnologiesAt GSoft Technologies, we've built login and authentication flows for dozens of mobile applications, from simple email/password forms to complex multi-factor authentication systems. A recent healthcare client required a HIPAA-compliant login system with biometric authentication, session timeout after inactivity, and encrypted local storage for tokens. We implemented this in Flutter using thelocal_authpackage for biometrics,flutter_secure_storagefor encrypted token storage, and a custom session management layer that automatically logs out inactive users.ConclusionBuilding a professional login screen in Flutter is a foundational skill that combines form management, state handling, validation, and UI design into one cohesive feature. The code in this tutorial gives you a production-ready starting point that you can extend with real authentication APIs, biometric login, and social sign-in providers. Contact GSoft Technologies to build your rs. Contact GSoft Technologies to build your next Flutter project â our team specializes in secure, beautiful, cross-platform mobile authentication flows.