Membuat Login Flutter dengan API Laravel (Flutter Authentication with Laravel)
In this article I will share tutorial How to make Flutter authentication with Laravel Rest API. This tutorial continues in part Membuat API Otentikasi Laravel (Laravel Rest API Authentication with Passport).
- Flutter, definitely.
- Laravel. (Here I will using Laravel 5.8)
- VS Code
Setup Laravel Backend
Read this detailed article specially for building basic authentication Laravel Rest API. Once you are ready, move to the next step.
Create a Flutter Application
Install Flutter Packages
We are going to use some Flutter packages:
http package, to consume HTTP resources.
shared_preferences package, providing a local storage for simple data.
Add the packages to your pubspec.yaml
Run the command flutter pub get
Note: You can use other versions of these packages according to the version of the Dart SDK you are using.
Create your project structure like below:
Within the lib directory create 2 folders:
- network ( create api.dart file )
- screens ( create login.dart, home.dart, register.dart files )
In the api.dart file, write a class that manages all API methods
Notice that, define String _url = ‘http://192.168.1.2/lara_passport/api/v1’ this is basically the base url for our Laravel API.
lara_passport is my laravel directory on XAMPP.
var token is a variable that will store API token for authentication and would be attached to every request that requires authentication.
We used SharedPreferences to allow us to store the logged in user to the local storage. Once the user has login to the application, does’nt have to login again.
This is the first class that run in your application. Here we will check if the user is authenticated and return to the home screen or the login screen.
You can copy and paste from the code below or build a form for yourself.
Define a boolean _isLoading = false; is to change the state of the login button text.
Define email and password variables, their values from their respective form fields after validation.
void _login() is a process to send a login data with an API. The results obtained from the API are read in JSON form. If you are successfully login, SharedPreferences will be store your account data and redirect to the Home Screen. If you can’t log in, it will display a notification _showMsg()
this file is similar to login.dart, significant change is in the form name field, and in the API route ‘/register’ as screen below:
At the initState() method is the first initialization method that is executed when the page is loaded. We call _loadUserData which returns the user data during register/login.
Here is my git repository for the Flutter auth with Laravel Rest API.
Having some issues? Let me know, write on comment below, cheers!