get data from one API that is dependent on another API flutter - flutter

Hello friends I am learning to build apps in Flutter. it's a single screen must display data from second api using user_id value from the first api.I have api response from server like this :
{
"code": 0,
"message": "",
"data": [
{
"userbox_id": 7,
"user_id": 53,
"box_id": 55,
"status": 0,
"created_at": "2021-04-28T11:55:12.000000Z",
"updated_at": "2021-04-28T11:55:12.000000Z"
},
{
"userbox_id": 8,
"user_id": 53,
"box_id": 56,
"status": 0,
"created_at": "2021-04-29T10:29:43.000000Z",
"updated_at": "2021-04-29T10:29:43.000000Z"
},
"error": [],
"status": 200
}
I would like to use "user_id" value to fetch data from second API response .
How i can do that ?
the first method:
Future<List<ActiveBox>> fetchBoxes() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
String token = localStorage.getString('access_token');
await checkInternet();
Map<String, String> headers = {
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token'
};
var url = Uri.parse(ApiUtil.GET_ALL_BOXES);
var response = await http.get(url, headers: headers);
switch (response.statusCode) {
case 200:
// print(response.statusCode);
var body = jsonDecode(response.body);
print(body);
List<ActiveBox> boxes = [];
for (var item in body['data']) {
boxes.add(ActiveBox.fromJson(item));
}
print(boxes);
inspect(boxes);
return boxes;
and the second method :
Future<User> getUser() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
String token = localStorage.getString('access_token');
print(token);
await checkInternet();
Map<String, String> headers = {
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token'
};
var url = Uri.parse(ApiUtil.GET_USER);
var response = await http.get(url, headers: headers);
switch (response.statusCode) {
case 200:
var body = jsonDecode(response.body);
User users = User.fromJson(body);
return users;
how i can implement that ? any help please

Related

In Flutter Is that possible to call API request in firebase Messaging BackgroundHandler?

I have implemented chat message app in which user can
reply to chat from push
notification when app is killed/background/foreground.
But when app is in Terminated state API call not work in
firebaseMessagingBackgroundHandler.
Its stuck on sendNotification function.
Code to handle background events:
Future<void>
firebaseMessagingBackgroundHandler(RemoteMessage message)
async {
await GetStorage.init();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform);
//Call HTTP request <Stuck here
sendNotification(
personUid,
title,
body,
notificationTypeId,
chatRoomId,
userTokenDummy,
userToken,
serverKey,
currentUserId,
currentUserToken,
);
}
Here is a code for API request:
sendNotification({
required String personUid,
required String title,
required String body,
required int notificationTypeId,
String? chatRoomId,
String? userTokenDummy,
String? userToken,
String? serverKey,
String? currentUserId,
String? currentUserToken,
}) async {
try {
final response = await http.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
HttpHeaders.contentTypeHeader:
'application/json',
HttpHeaders.authorizationHeader: 'key=$serverKey'
},
body: jsonEncode(
<String, dynamic>{
"data": <String, dynamic>{
"title": title,
"body": body,
"click_action": "FLUTTER_NOTIFICATION_CLICK",
"id": "1",
"status": "done",
"senderId": currentUserId,
"senderToken": currentUserToken,
"notificationTypeId": notificationTypeId,
"chatRoomId": chatRoomId,
},
"android": {
"priority": "high",
},
"apns": {
"headers": {"apns-priority": "10"}
},
"to": userToken,
"content_available": true,
"mutable-content": 1,
"priority": "high",
},
),
);
return response;
} catch (e) {
console(e.toString());
}
}
Yes,you can call Http request inside firebaseMessagingBackgroundHandler. But make sure that this api is not taking too much time. Because long and intensive tasks impacts on device performance. Also make sure that there is not exception or error in the api which causes the device to freeze.
To make sure that api is not running forever place a timeout in http class.
for more refer to firebase documentation : https://firebase.google.com/docs/cloud-messaging/flutter/receive

Flutter Dio NO_RENEGOTIATION(ssl_lib.cc:1725) error 268435638

I have a problem when I make a http request to the server
when I post on flutter it returns NO_RENEGOTIATION(ssl_lib.cc:1725) error 268435638 error, but when I try to use postman it works fine.
I've equated all the headers with postman, replaced Jcenter() with MavenCentral() and it doesn't work
This is the code I use:
final Map<String, dynamic> requestData = {
"email": Encryption().encryptKey(email),
"password": Encryption().encryptKey(password),
"user_ad": userType,
"token_fcm": _tokenFcm,
"is_encrypted": true,
};
Response response = await _dio.post(
"$basePath/login",
data: FormData.fromMap(requestData),
options: Options(
headers: {
"Connection": "keep-alive",
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, br",
"Host": "btnsmartdev.btn.co.id",
"Content-Type": "application/json",
"Cache-Control": "no-cache",
"Content-Length": "173"
},
validateStatus: (status) {
print("INI STATUS");
print(status);
return (status ?? 0) < 500;
},
followRedirects: false,
)
);
final data = response.data;
Here's what I get in terminal:
Here's the request from postman:

How make a http post with Dio using data raw in flutter?

I'm trying to do a dio post request and I need to specify the body as raw-data Post
Response response = await (await init()).post(url, data: {
"token": token,
"code": formol}
);
Try to encode it as a Json:
var json = {
"code": "xxxxxxxxx",
"token": "-------------",
};
...
Response response = await _dio.post(url,
options: Options(headers: {
HttpHeaders.contentTypeHeader: "application/json",
}),
data: jsonEncode(json),
);

Issue with uploading multi part image file with dio in Flutter

I used Dio framework to upload image to server in my flutter app. Dio version 3.0.9.
Post method.
Added 4 headers
Created form data with image and other fields.
I have analysed many more methods. Like degrading Dio to 2.3.1, to use UploadFileInfo method. Not a success. Then with multipartfileupload. Finally this one.
Future<bool> createStoreWithDio() async {
Map<String, String> headers = {
"Accept": "application/json",
"authorization": tokenString,
"authtype": "admin",
"Content-Type": "multipart/form-data"
};
try {
FormData formData = new FormData.fromMap({
"logo": await http.MultipartFile.fromPath("logo", imageFile.path,
contentType: new MediaType('image', 'png')),
"name": " Bala ios",
"description": "_description",
"website": "www.website.com",
"password": "Test password",
"user_name": "Test userInformationName",
"mobile": "9988776655",
"email": "test#techit.io",
});
print(formData.fields);
Response response = await dio
.post(
"API",
data: formData,
options: Options(
headers: headers,
),
)
.then((value) {
print(value.toString());
});
print(response.toString());
} catch (error) {
print(error);
}
}
imageFile is the file I captured from camera/ gallery.
I am getting 500 exception. Any help would be helpful
I am not sure what caused this,this code is used in an app i have change based on your code,but i am not sending any headers so you need to add then try with this code let me know it it's work for you.also make sure you have file imageFile.path also your api url is correct or not
make sure you have imported
`'import package:http_parser/http_parser.dart';
import 'package:mime/mime.dart';`
Dio dio = new Dio();
final mimeTypeData =
lookupMimeType(imageFile.path, headerBytes: [0xFF, 0xD8]).split('/');
FormData formData = FormData.fromMap({
"name": " Bala ios",
"description": "_description",
"website": "www.website.com",
"password": "Test password",
"user_name": "Test userInformationName",
"mobile": "9988776655",
"email": "test#techit.io",
"logo": await MultipartFile.fromFile(imageFile.path,
contentType: MediaType(mimeTypeData[0], mimeTypeData[1])),
});
var response = await dio.post(
Urls.ImageInsert,
data: formData,
);
var message = response.data['message'];

How to handle restful web service response in react native?

This is how I'm calling a web service.
fetch('http://**someurl**', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username : "admin",
password: "admin123",
})
})
When I call it from postman I get a response like this :
{
"code": 1,
"message": {
"Object1": [
{
"Id": 1,
"Name": "COWDUNG",
"manufacturer": "OWN",
"description": "ORGANIC MANUER",
"type": "Fertilizer"
}
]
}
}
Can anyone tell me how to handle the response?
Hope this helps.
fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username : "admin",
password: "admin123",
})
}).then((response) => response.json()).then((responseJson) => {
// you'll get the response in responseJson
})
.catch((error) => {
//you will get error here.
});