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

Yusuf Biberoğlu
1 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 Udemy Course;

Flutter: Google Sign In with REST API, JWT

https://www.udemy.com/course/flutter-google-sign-in-with-rest-api-jwt/?referralCode=39B955A0C1C5AAFA8A93

Discount Code:

https://www.udemy.com/course/flutter-google-sign-in-with-rest-api-jwt/?couponCode=B6728A76327637F4BEE6

--

--