Flutter: Basic Authentication | Login | Sign in with dio package

Yusuf Biberoğlu
2 min readFeb 21, 2023

In this article i want to show how to do Basic auth to get token using Dio and retrieve data from a specified URL with token.

Run this command:

 flutter pub add dio

Don’t forget headers:

import 'package:dio/dio.dart';
....

Future<Response?> signIn() async {
var dio = Dio();
try {
var response = await dio.post('https://localhost:8000/authentication',
data: {"email": "user@email.com", "password": "123456"},
options: Options(
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
));
print(response.data);
return response;
} catch (e) {
print(e.toString());
}
return null;
}
ElevatedButton.icon(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.white,
foregroundColor: Colors.black,
minimumSize: Size(double.infinity, 50)),
onPressed: () {
signIn();
},
icon: Icon(Icons.login),
label: Text('Sign In'),
),

An access-token through GET request method to retrieve data from a specified URL

var getUserInfo = await dio.get('https://localhost:8000/users/me',
options: Options(
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer ${response.data["token"]} ',
},
));

print(getUserInfo);

My YouTube Channel;

If you find this useful, please don’t forget to clap 👏 and follow me. I will continue according to your request.

My Udemy Course;

Symfony application using Google OAuth for authentication. When a user signs in through Google, our system will check if the user already exists in our database. If not, it will create a new user account. Once authenticated, either as a new or existing user, our application will generate a JSON Web Token (JWT). Built on the API Platform.

I have explained below which commands we need. If you want a detailed explanation, please purchase my Udemy course.

https://www.udemy.com/course/google-oauth-php-symfony-api-platform-jwt/?referralCode=67A58BBAE3151CDC1255

Discount Coupon: AD25A625CB8976085C88

--

--