Reputation: 103
im trying to request data from my API and to get the data, it requires a bearer token which can be obtain by log-in. and as a frontend I created a function to save and request from the UI to the API. I'm using flutter framework for the UI.
I've managed to create a function to store the bearer token generated at login, which keeps the user logged in. and it works by saving the bearer token in sharedpref.
login() async {
final response = await http.post(
"https://api.batulimee.com//v1_ship/login_app",
body: {"email": email, "password": password},
);
final data = jsonDecode(response.body);
String status = data['status'];
String pesan = data['message'];
String apikey = data['data']['apikey'];
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('apikey', apikey);
if (status == "success") {
Navigator.of(context).pushReplacement(PageRouteBuilder(
pageBuilder: (_, __, ___) => new bottomNavBar(),
transitionDuration: Duration(milliseconds: 600),
transitionsBuilder:
(_, Animation<double> animation, __, Widget child) {
return Opacity(
opacity: animation.value,
child: child,
);
}));
print(pesan);
print(apikey);
} else {
print(pesan);
}
}
heres the response.
{
"status": "success",
"data": {
"apikey": "UUFmb0w3WlI4Q01qOWRTamgxOFVZRjhIeWhFMkN3T205R20xZXNpYw==",
"id_user": 50,
"id_role": "8",
"name_role": "Ship Owner",
"email": "[email protected]",
"phone": "0210201",
"saldo": "0",
"photo": "https://cdn.batulimee.com/foto_user/avatar.png"
},
"message": "login successfully "
}
and now I want to create a function that can get user profile data, and where to get this data requires the bearer token which I got from login. I need this so that the user can edit their name, password, or other data in the user's profile and save it.
My backend has created the API get my_profile. which I explained earlier, to get this requires a token bearer that is the same as the token bearer we got earlier from login. And now it's my job to get the get my_profile data using a function in flutter.
heres the response from the API get my_profile.
{
"status": "success",
"data": {
"id_user": 49,
"id_role": "8",
"name_role": "Ship Owner",
"first_name": "a",
"last_name": "f",
"email": "[email protected]",
"phone": "082258785595",
"saldo": "0",
"company_name": "aa",
"company_address": "jl kav pgri",
"photo": "https://batulimee.com/foto_user/avatar.png"
},
"message": "get profile detail successfully "
}
How is the function to store the bearer token into Authorization so I can get my_profile data ? please help me.... :(
Upvotes: 1
Views: 949
Reputation: 116
make an api class :
import 'package:http/io_client.dart';
class Api {
String _token;
final Client http =IOClient(HttpClient()
..badCertificateCallback = _certificateCheck
..connectionTimeout = const Duration(seconds: kConnectionTimeoutSeconds));
static bool _certificateCheck(X509Certificate cert, String host, int port) =>
host.endsWith('EXAMPLE.com'); // Enter your url for api here
String GetToken() {
return _token;
}
Future<bool> setToken(String token) async {
_token = token;
return Future.value(true);
}
Map<String, String> get headers => {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": "Bearer $_token",
};
}
in your login use the setToken:
await _api.setToken(apikey);
next for your profile or any request in api class:
Future<ProfileResponse> getProfile() async {
var url = "$urlPrefix/api/v1/profile";
var response = await http.get(url, headers: headers);
if (response.statusCode != 200) {
print(
"$response");
var parsed = json.decode(response.body);
var message = parsed["message"];
if (message != null) {
throw message;
}
throw Exception(
"Request to $url failed with status ${response.statusCode}: ${response.body}");
}
// return the response you want
return json.decode(response.body);
}
Upvotes: 1