Hereโs a step-by-step guide to creating a Login Form in Flutter, along with complete working code you can copy and run.
๐ Step 1: Create a New Flutter Project
Run this in your terminal:
flutter create login_app
cd login_app
๐งฑ Step 2: Understand What Weโll Build
Weโll create:
- Email field
- Password field
- Login button
- Basic validation
๐ Step 3: Open main.dart
Go to:
lib/main.dart
Replace everything with the code below ๐
๐ป Full Flutter Login Form Code
import 'package:flutter/material.dart';void main() {
runApp(MyApp());
}class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: LoginScreen(),
);
}
}class LoginScreen extends StatelessWidget {
final _formKey = GlobalKey<FormState>(); final TextEditingController emailController = TextEditingController();
final TextEditingController passwordController = TextEditingController(); @override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Login Form"),
centerTitle: true,
),
body: Padding(
padding: const EdgeInsets.all(20.0),
child: Form(
key: _formKey,
child: Column(
children: [
// Email Field
TextFormField(
controller: emailController,
decoration: InputDecoration(
labelText: "Email",
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || value.isEmpty) {
return "Please enter your email";
}
if (!value.contains("@")) {
return "Enter a valid email";
}
return null;
},
), SizedBox(height: 20), // Password Field
TextFormField(
controller: passwordController,
obscureText: true,
decoration: InputDecoration(
labelText: "Password",
border: OutlineInputBorder(),
),
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: 30), // Login Button
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
String email = emailController.text;
String password = passwordController.text; ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("Login Successful\nEmail: $email"),
),
);
}
},
child: Text("Login"),
),
],
),
),
),
);
}
}
โถ๏ธ Step 4: Run the App
flutter run
โจ Step 5: What You Learned
TextFormFieldfor inputsForm+GlobalKeyfor validationTextEditingControllerto get input valuesElevatedButtonfor actions- Basic validation logic
๐ฏ Optional Improvements
You can enhance your login form by adding:
- ๐ Show/Hide password toggle
- ๐ฑ Responsive UI using
MediaQuery - ๐ API authentication
- ๐จ Better UI with
Container,BoxDecoration, gradients
๐ก Bonus: Add Show/Hide Password
Replace password field with:
bool isHidden = true;TextFormField(
obscureText: isHidden,
decoration: InputDecoration(
labelText: "Password",
border: OutlineInputBorder(),
suffixIcon: IconButton(
icon: Icon(isHidden ? Icons.visibility : Icons.visibility_off),
onPressed: () {
isHidden = !isHidden;
},
),
),
)