Flutter: Managing sessions.
In computer science, a session is a semi-permanent interactive information interchange between a computer and a user. A session is set up or established at a certain point in time and then torn down at some later point.
Note: Before moving forward with this article please read my other article on Dependency Injection for a better understanding.
In the Flutter app, to understand the session, let us first know about the API request, response, and authentication for making an API request.
Request: Request is the process of a client application calling an endpoint of an API and that API retrieving the requested data from the external server or program.
Response: Response is the process in which an external server or a program responds to a respective request.
Authentication process: The API authentication process validates the identity of the client attempting to make a connection by using an authentication protocol. The protocol sends the credentials from the remote client requesting the connection to the remote access server in either plain text or encrypted form. The server then knows whether it can grant access to that remote client or not.
While making an API request, there are pieces of information that need authentication to access or edit. So to provide authorization, we have an authentication header in every API request.
Using Dio as an HTTP client
What is Dio?
Dio is a powerful HTTP client for Dart, which supports Interceptors, Global configuration, FormData, Request Cancellation, File downloading, Timeout, etc.
Making an API request using Dio
In the above example, we can make a request by providing the access token in the authorization header.
But when the complexity of the application increases then we must send this token to each request separately. And in such a large application, this will get tedious.
Let us make a singleton class that handles all the requests.
Now, this singleton class Request
handles all the API requests using Dio
object.
Now let us make a Get
request.
Here, I’ve set the end-point as hi
and set the initial token as noToken
Now, Let us update the token when the user logs in.
request.updateSession('updated-token');
Here, I’ve set the end-point as pie
and set the initial token as updated-token
Real-world use case
- Whenever the user logs in, update the authorization with
updateSession()
method. - Whenever you check the user persistence, update the authorization with
updateSession()
method.
In this way, You can handle any kind of API request without worrying about the authorization of the API.