FlutterRestAPIJWT
Last updated at 2023-10-22

Flutter REST API Auth with JWT

ClickUp
Note
AI Status
75%
Last Edit By
Last edited time
Oct 22, 2023 08:53 AM
Metatag
Slug
flutter-auth-jwt-rest-api
Writer
Published
Published
Date
Oct 22, 2023
Category
Flutter
RestAPI
JWT
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:

Setting up the Flutter Project

  1. Create a new Flutter project by running the following command:
    1. flutter create flutter_login_jwt
  1. Navigate to the project directory:
    1. cd flutter_login_jwt
  1. 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.
  1. Open the pubspec.yaml file and add the following dependencies:
    1. dependencies: flutter: sdk: flutter http: ^0.13.4 jwt_decoder: ^1.1.0
  1. Save the file and run the following command to fetch the dependencies:
    1. flutter pub get

Implementing the Login Screen

Now let's implement the login screen UI and functionality.
  1. Replace the code in the lib/main.dart file with the following code:
    1. 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!'), ), ); } }
  1. Replace http://your-api-url.com/login in the _login method with the actual URL of your backend API endpoint for user authentication.
    1. Note: Make sure your backend API returns a JWT token upon successful authentication.
  1. Save the file and run the application using the following command:
    1. 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:
Happy coding!

Discussion (0)

Related Posts