Flutter Login, Register and Logout using Rest-API http Post request.
In this article we will be implementing a simple login, register and logout system in flutter using http Post request. We will be using reqres, an online hosted Rest-API server to test our simple system.
RESTful-API allows us to use the protocols of HTTP in a structured and decent way. It gives developers more flexibility to use basic protocols like GET, POST, DELETE, etc. We can use this API in Flutter to create an authentication system. In this system, we can generate a POST method to pass login or registration parameters to a server and the server will send us the response based on the parameters that are sent. In response, we can get feedback from the server. The response could be a successful message and a key that denotes a successful request or an error message if the request is not properly satisfied.
Things we will be covered in this article are:
- How to create an HTTP POST request for Login and Registration.
- How to collect the response and manage it.
- How to hold the key of a successful response until logout.
- How to execute logout.
1. Initial Setup:
Create a new Flutter project and in Your pubspec.yml file add the following dependencies.
http: ^0.12.2
shared_preferences: ^0.5.12
HTTP dependency is for operating HTTP protocols and shared_preferences is to store a non-trivial short amount of data. We will store the authentication key for a successful login or registration in here and carry it to the service pages to authenticate the user.
We will keep the structure simple. So, create two dart files in the lib directory. One for the login page and another for the registration page. We will use the main.dart file as the home page. If the user logged in or registered successfully then he will be directed in this page or he will stay at the login or register page.
2. Login and Register:
We are using reqres online hosted server for login and registration. Here the parameters for Login and Register are the same. Generally, the registration form contains more fields than log in. The form will change based on the parameters the login or register form contains. Basically, the required parameters are presented in the JSON format.
First we will see the Login process then we will talk about the Registration. The parameters for login is presented below,
{
"email": "eve.holt@reqres.in",
"password": "cityslicka"
}
For login, there must have to be a form of text fields from where the values against every required parameter will be collected and pass to the function what will create the POST request. The values are collected from the text fields and put them in variables like this-
final TextEditingController emailController = new TextEditingController();
final TextEditingController passwordController = new TextEditingController();
Then the signIn class is called with these parameters. The signIn class receives the values and map them with the parameters of the JSON format. This JSON format is stored in a variable and passed with the post request as like this-
var response = await http.post("Link of the server", body: json formated data);
After a successful request, it will return a status code 200 what denotes that the request has proceeded successfully. If the request is unsuccessful then the status code will be changed and will return an error message. If it is a successful response then we will get the key and navigate it to the home page and if it is not then we will show the error message on the Login Page. The whole code of the login page is given below-
https://github.com/NahidAkhtar84/flutter_login_register/blob/master/lib/login_page.dart
Here, the registration form code is identical because the parameters for Login and registration are same. The code of registration page is given below-
https://github.com/NahidAkhtar84/flutter_login_register/blob/master/lib/register_page.dart
3. Holding authentication data
Now, we have registered or logged in successfully but we need to keep ourselves logged in as a valid user in our application, Right? We can do this with the help of shared_preferences library. For this, we have to initialize shared_preferrences in our logIn and Registration page like this-
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
If the response is successful, Then, we can put the response key into this sharedPreferences variable and pass it to the home page to validate the user.
sharedPreferences.setString("token", jsonResponse['token']);
4. Home Page and Logout
In the home page we will check the sharedPreferrences value. If it is null then we will navigate to login page, otherwise the user will stay at the home page.
loginStatus() async {
sharedPreferences = await SharedPreferences.getInstance();
if(sharedPreferences.getString("token") == null) {
Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (BuildContext context) => LoginPage()), (Route<dynamic> route) => false);
}
}
For Logout we have to place a button at the home page and on it’s onpressed function we have to clear the sharedPreferences value and navigate back to the login Page.
onPressed: () {
sharedPreferences.clear();
sharedPreferences.commit();
Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (BuildContext context) => LoginPage()), (Route<dynamic> route) => false);
}
The whole code of the home page is given below-