How To Create a Login Screen in Flutter Using Laravel Backend
Table of Contents
How to Create a Login Screen in Flutter? Flutter is a google framework which use the dart language. Using Fluter framework you can develop android and iOS application. The flutter is a frontend framework which use to design ui/ux mobile applications
In this tutorial we will discuss how to create login screen in flutter .Creating a sleek and functional login screen is a fundamental part of developing any app. In this tutorial, we’ll guide you through the process of building a simple login screen using Flutter.
Follow along to learn how to create a login screen in Flutter using Laravel backend with ease.
Prerequisites
Before creating your project make sure you have installed the Flutter sdk and Laravel composer in your pc or labopt.
- Flutter installed on your system.
- A basic understanding of Flutter widgets and Dart programming.
- Knowledge of PHP Laravel framework.
Step 01: Create new laravel project for this copy the below code and past it in your terminal.
composer create-project laravel/laravel Flutter_Login
- After creating your project open your .env file in your root directry and put your database info like db name, user and password.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=foodorder_app
DB_USERNAME=root
DB_PASSWORD=
2. Open your terminal in your project root and type below command for database migration.
php artisan migrate
The above command will migrate your user table in the Mysql Database which you recently connect in your .env file.
3. Next step to create controller in which we creeate the all methods for login, register and logout. So in your terminal enter the below command.
php artisan make controller AuthController
The AuthController in exist in your apphttpcontrollersAuthControoler. So open your auth controller and copy the below code and in past in your controller.
<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use AppModelsUser;
use IlluminateSupportFacadesHash;
use IlluminateValidationValidationException;
class AuthController extends Controller
{
public function register(Request $request)
{
$request->validate([
‘name’ => ‘required|string’,
’email’ => ‘required|string|email|unique:users’,
‘password’ => ‘required|string|min:6’,
]);
$user = User::create([
‘name’ => $request->name,
’email’ => $request->email,
‘password’ => Hash::make($request->password),
]);
return response()->json([‘message’ => ‘User registered successfully!’]);
}
public function login(Request $request)
{
info($request);
$request->validate([
’email’ => ‘required|string|email’,
‘password’ => ‘required|string’,
]);
$user = User::where(’email’, $request->email)->first();
if (!$user || !Hash::check($request->password, $user->password)) {
throw ValidationException::withMessages([
’email’ => [‘The provided credentials are incorrect.’],
]);
}
$token = $user->createToken(‘authToken’)->plainTextToken;
return response()->json([‘token’ => $token]);
}
public function logout(Request $request)
{
$request->user()->currentAccessToken()->delete();
return response()->json([‘message’ => ‘Logged out successfully.’]);
}
public function user(Request $request)
{
return response()->json($request->user());
}
}
4. The final step is to make the api route for login request . go to your project root directory and open api.php in your route directory and copty the below api route and past.
use AppHttpControllersAuthController;
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Route::post(‘/register’, [AuthController::class, ‘register’]);
Route::post(‘/login’, [AuthController::class, ‘login’]);
Now your backend api has successfuly created and your can test it in post man.
http://127.0.0.1:8000/api/login
How to Create Login Screen in Flutter Using Laravel Backend
Step 02: Create design ui/us for login screen in Flutter
01: Open your terminal or IDE and create a new Flutter project:
flutter create login_screen_demo
02: Navigate to the project directory:
cd login_screen_demo
03: Open the project in your preferred code editor (e.g., Visual Studio Code or Android Studio)
In the lib folder, open the main.dart file and replace its content with the following:
import 'package:flutter/material.dart';
import ‘../screens/login_screen.dart’;
import ‘../screens/home_screen.dart’;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.deepOrange,
hintColor: Colors.amber,
fontFamily: ‘Raleway’,
),
routes: {
‘/login’: (_) => LoginScreen(),
‘/home’: (_) => HomeScreen(),
initialRoute: ‘/login’,
);
}
}
2. Create service_api.dart in your lib folder make base api path and login function .
//how to create a login screen in flutter
import ‘package:http/http.dart’ as http;
import ‘package:shared_preferences/shared_preferences.dart’;
import ‘../Model/menu_item.dart’;
import ‘dart:io’ as io;
class ApiService {
static const String baseUrl = ‘http://127.0.0.1:8000/api’;
//static const String baseUrl = ‘http://10.0.2.2:8000/api’;
//static const String
static Future<Map<String, dynamic>> login(String email, String password) async {
try {
final response = await http.post(
Uri.parse(‘$baseUrl/login’),
headers: {‘Content-Type’: ‘application/json’},
body: json.encode({’email’: email, ‘password’: password}),
);
print(‘Request: ${response.request}’);
print(‘Response: ${response.statusCode}’);
print(‘Body: ${response.body}’);
return json.decode(response.body);
} catch (e) {
print(‘Error: $e’);
return {‘error’: ‘An error occurred while connecting to the server’};
}
}
3. Next step is to create login screen.dart in your lib directory and past the following code.
//how to create a login screen in flutter
import ‘../api/api_service.dart’;
class LoginScreen extends StatelessWidget {
final TextEditingController emailController = TextEditingController();
final TextEditingController passwordController = TextEditingController();
void login(BuildContext context) async {
final response = await ApiService.login(
emailController.text,
passwordController.text,
);
if (response.containsKey(‘token’)) {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(‘token’, response[‘token’]);
Navigator.pushReplacementNamed(context, ‘/home’);
} else {
// Handle error
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(‘Login failed’)),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(‘Login’),
backgroundColor: Colors.red, // AppBar red color
),
body: SingleChildScrollView( // Enable scrolling for smaller screens
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
// Top centered login image
Center(
child: Image.asset(
‘assets/login_image.png’, // Your image asset
height: 150,
),
),
SizedBox(height: 30), // Space between image and input fields
// Email Input with Icon
TextField(
controller: emailController,
decoration: InputDecoration(
labelText: ‘Email’,
prefixIcon: Icon(Icons.email, color: Colors.black),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8.0),
),
filled: true,
fillColor: Colors.grey[200], // Light grey background for input
),
),
SizedBox(height: 16), // Space between input fields
// Password Input with Icon
TextField(
controller: passwordController,
obscureText: true,
decoration: InputDecoration(
labelText: ‘Password’,
prefixIcon: Icon(Icons.lock, color: Colors.black),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8.0),
),
filled: true,
fillColor: Colors.grey[200], // Light grey background for input
),
),
SizedBox(height: 24), // Space between input and button
// Login Button (Full-width with black background)
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: () => login(context),
style: ElevatedButton.styleFrom(
primary: Colors.black, // Button background color
padding: EdgeInsets.symmetric(vertical: 16), // Button height
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8.0), // Rounded corners
),
),
child: Text(
‘Login’,
style: TextStyle(
color: Colors.white, // Text color white
fontSize: 16,
),
),
),
),
SizedBox(height: 16),
// Space between button and footer
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: () => login(context),
style: ElevatedButton.styleFrom(
primary: Colors.black, // Button background color
padding: EdgeInsets.symmetric(vertical: 16), // Button height
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8.0), // Rounded corners
),
),
child: Text(
‘Sign UP’,
style: TextStyle(
color: Colors.white, // Text color white
fontSize: 16,
),
),
),
),
],
),
),
),
);
}
}
Conclusion
Congratulations! You’ve successfully learned how to create a login screen in Flutter using Laravel framework. Feel free to customize the design and functionality to suit your app’s needs. Stay tuned for more tutorials!
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.