In this article, we will learn how to implement a login functionality in a Flutter application using JWT (JSON Web Tokens) for authentication.
Flutter is a popular cross-platform framework for building mobile applications.
Prerequisites
Before we start, make sure you have the following prerequisites installed:
- Flutter SDK: Install Flutter
- Dart SDK: Install Dart
Setting up the Flutter Project
- Create a new Flutter project by running the following command:
flutter create flutter_login_jwt
- Navigate to the project directory:
cd flutter_login_jwt
- Open the project in your favorite code editor.
Adding Dependencies
To implement JWT authentication in our Flutter application, we need to add some dependencies to our
pubspec.yaml
file.- Open the
pubspec.yaml
file and add the following dependencies:
dependencies: flutter: sdk: flutter http: ^0.13.4 jwt_decoder: ^1.1.0
- Save the file and run the following command to fetch the dependencies:
flutter pub get
Implementing the Login Screen
Now let's implement the login screen UI and functionality.
- Replace the code in the
lib/main.dart
file with the following code:
import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:jwt_decoder/jwt_decoder.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Login with Auth JWT', theme: ThemeData( primarySwatch: Colors.blue, ), home: LoginPage(), ); } } class LoginPage extends StatefulWidget { @override _LoginPageState createState() => _LoginPageState(); } class _LoginPageState extends State<LoginPage> { final TextEditingController _emailController = TextEditingController(); final TextEditingController _passwordController = TextEditingController(); bool _isLoading = false; Future<void> _login() async { setState(() { _isLoading = true; }); final String email = _emailController.text.trim(); final String password = _passwordController.text.trim(); // Make a POST request to your backend API to authenticate the user final response = await http.post( Uri.parse('<http://your-api-url.com/login>'), body: { 'email': email, 'password': password, }, ); if (response.statusCode == 200) { // Successful login // Extract the token from the response body final token = jsonDecode(response.body)['token']; // Decode the token to get the user information final Map<String, dynamic> decodedToken = JwtDecoder.decode(token); // TODO: Save the token and user information for future use // Navigate to the home screen Navigator.pushReplacement( context, MaterialPageRoute(builder: (context) => HomeScreen()), ); } else { // Failed login showDialog( context: context, builder: (context) => AlertDialog( title: Text('Error'), content: Text('Invalid email or password'), actions: [ TextButton( onPressed: () => Navigator.pop(context), child: Text('OK'), ), ], ), ); } setState(() { _isLoading = false; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Login'), ), body: Padding( padding: const EdgeInsets.all(20.0), child: Column( children: [ TextField( controller: _emailController, decoration: InputDecoration( labelText: 'Email', ), ), SizedBox(height: 20.0), TextField( controller: _passwordController, obscureText: true, decoration: InputDecoration( labelText: 'Password', ), ), SizedBox(height: 20.0), ElevatedButton( onPressed: _isLoading ? null : _login, child: _isLoading ? CircularProgressIndicator() : Text('Login'), ), ], ), ), ); } } class HomeScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Home'), ), body: Center( child: Text('Welcome to the Home Screen!'), ), ); } }
- Replace
http://your-api-url.com/login
in the_login
method with the actual URL of your backend API endpoint for user authentication.
Note: Make sure your backend API returns a JWT token upon successful authentication.
- Save the file and run the application using the following command:
flutter run
This will launch the application on an emulator or connected device.
Conclusion
In this article, we learned how to implement a login functionality in a Flutter application using JWT for authentication.
We covered the setup process, adding dependencies, and implementing the login screen UI and functionality.
You can now customize the UI and integrate the JWT token and user information handling according to your application's requirements.
For more information on Flutter and authentication, refer to the following resources:
- Flutter Documentation: https://flutter.dev/docs
- JWT Package Documentation: https://pub.dev/packages/jwt_decoder
- HTTP Package Documentation: https://pub.dev/packages/http
Happy coding!