
How to create login page and then navigate on next screen using Flutter
Creating a login page and navigating to the next screen in Flutter involves the following steps:
1. Set Up a Basic Flutter App
If you haven’t already:
flutter create login_app
cd login_app
2. Define the File Structure
You can follow a simple structure:
/lib
main.dart
login_page.dart
home_page.dart
3. main.dart
This file will set up the initial route.
import 'package:flutter/material.dart';
import 'login_page.dart';
import 'home_page.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Login Demo',
theme: ThemeData(primarySwatch: Colors.blue),
initialRoute: '/',
routes: {
'/': (context) => LoginPage(),
'/home': (context) => HomePage(),
},
);
}
}
4. login_page.dart
This is your login UI. It checks credentials and navigates to the home screen.
import 'package:flutter/material.dart';
class LoginPage extends StatefulWidget {
@override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
final _usernameController = TextEditingController();
final _passwordController = TextEditingController();
String? _errorText;
void _login() {
String username = _usernameController.text;
String password = _passwordController.text;
// Dummy authentication
if (username == 'admin' && password == '1234') {
Navigator.pushReplacementNamed(context, '/home');
} else {
setState(() {
_errorText = 'Invalid username or password';
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Login')),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
TextField(
controller: _usernameController,
decoration: InputDecoration(labelText: 'Username'),
),
TextField(
controller: _passwordController,
obscureText: true,
decoration: InputDecoration(labelText: 'Password'),
),
if (_errorText != null)
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Text(
_errorText!,
style: TextStyle(color: Colors.red),
),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: _login,
child: Text('Login'),
)
],
),
),
);
}
}
5. home_page.dart
This is the screen after login.
import 'package:flutter/material.dart';
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Home Page')),
body: Center(
child: Text(
'Welcome to the Home Page!',
style: TextStyle(fontSize: 24),
),
),
);
}
}
Result
- Enter username:
admin
- Enter password:
1234
- Tap “Login” → Navigates to HomePage
Bonus: Best Practices for Production
- Use form validation (
Form
,TextFormField
). - Manage state with Provider, Bloc, or Riverpod.
- Store session/token securely using
flutter_secure_storage
.