I am new to flutter and am trying to receive a response that is returned when I do a post request. I want to display the response object in a preview modal however, i am stuck on how to go about it. I have so far been able to hit the post endpoint successfully and a console.log shows me the response as I expected. How can I receive the response and assign it to a variable that I can then pass to a view modal?
Here is what I have done so far:
/* The Post DbRequest */
Future < Reservation ? > priceReservation(Reservation priceReservation) async {
var content = jsonEncode(priceReservation.toJson());
const baseUrl = ApiEndPoint.baseUrl;
searchUrl = '$baseUrl/reservation/price';
var response = await http.post(
Uri.parse(searchUrl),
body: content,
headers: {
"Content-Type": "application/json"
},
);
final data = json.decode(response.body);
if (response.statusCode == 202) {
print(data);
return data;
} else
print(data);
return null;
}
/* The Post Service */
priceReservation(priceReservation) async {
ReservationDbRequests requests = ReservationDbRequests();
Reservation ? reservation =
await requests.priceReservation(priceReservation);
return reservation;
}
/* How can I receive the response in this save method and assign it the data variable */
_save() async {
if (_formKeyBooking.currentState!.validate()) {
Reservation reservationObject = new Reservation(
roomId: _roomController.text,
email: _emailController.text,
quantity: _quantityController.text.toString(),
checkInDate: DateTime.parse(_checkInController.text),
checkOutDate: DateTime.parse(_checkOutController.text),
);
Response data = await Provider.of < BookingService > (context, listen: false)
.priceReservation(reservationObject);
print(data);
setState(() {
_isLoading = false;
});
toastMessage(ToasterService.successMsg);
} else {
toastMessage(ToasterService.errorMsg);
}
}
// Here is my response
{
"id": "c204b78b-cae3-44ea-9aaf-2f439488fef9",
"email": "adeleke#email.com",
"quantity": 1,
"nights": 5,
"totalPricePerRoomPerNight": 134.07,
"totalPrice": {
"rooms": 615.0,
"discounts": 0.0,
"taxes": 55.35,
"total": 670.35
},
"room": {
"id": "d54986a8-4e00-4332-8edc-acf6e380f6c4",
"name": "villa",
"price": 123.0
},
"checkInDate": "2021-09-29T12:00:00+03:00",
"checkOutDate": "2021-10-04T12:00:00+03:00",
"taxes": [
{
"name": "room services",
"percent": 9.0,
"amount": 11.07
}
],
"discounts": []
}
will this help? check this artilcle for json serilization for complex response
Future <Map<String,dynamic>?> priceReservation(Reservation priceReservation) async {
//you API access code goes here
//check the status first before decoding
if (response.statusCode == 200) { //got the response with data
return json.decode(response.body);
} else if (response.statusCode == 204) { //got the response but no data
return null;
} else { //throw exception for other status code
throw 'error';
}
}
/* The Post Service */
Future<Map<String,dynamic>?> priceReservation(priceReservation) async {
ReservationDbRequests requests = ReservationDbRequests();
Map<String,dynamic>? response =
await requests.priceReservation(priceReservation);
return response;
}
//view
Map<String,dynamic>?> response = await Provider.of < BookingService > (context, listen: false)
.priceReservation(reservationObject);
print(response); //now it should be a Map
if(response != null){
print(response); //all response
print(response['id']); //access id
print(response['email']); //access email
print(response['room']['name']); //access room name
}
Related
How to make api class where api response start with array ?
Api Response :-
[
{
"reqList": [
{
"_id": "123448478478",
"username": "12345",
"amount": 4100
},
],
"_id": "636e2c5cf0142eed68343335",
"username": "umesh-rajput",
"amount": 95
}
]
We can handle this response as a list of individual JSON objects inside the response array.
This is general Pseudo code.
class DataProvider{
List<YourModel> getDate(String URL) async {
var response = await http.get(url);
if(resonse.statuscode == 200)
{
var List<YourModel> modelList =
response.body.map((jsonObject)=>YourModel.toJson(jsonObject);
);
return modelList;
}
return [];
}
}
Future<List<MODEL NAME>> getAllBetNotification() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var token = prefs.getString('userToken');
url = 'API URL';
var response = await http.get(Uri.parse(url), headers: {
'Authorization': 'YOUR TOKEN',
});
if (response.statusCode == 200 || response.statusCode == 201) {
// print(response.body);
var list1 = (jsonDecode(response.body) as List)
.map((dynamic i) =>
UserNotificationModel.fromJson(i as Map<String, dynamic>))
.toList();
return list1;
} else {
print('do not send notification');
return [];
}
}
code for api_addEvent.dart
class ApiAddEventToCalender {
Future<ApiResponseData> addEventToCalender(
String token,
String date,
String time,
String previousEventDocID,
int eventDateEpocMilisecond) async {
ApiResponseData apiResponseData =
ApiResponseData(responseCode: "27", responseMsg: "Unknown Error");
var url = '${Constants.apiEndPoint}/addEventToCalender';
if (date.length < 1) {
ApiResponseData apiResponseData =
ApiResponseData(responseCode: "17", responseMsg: "Invalid date.");
return apiResponseData;
}
if (eventTitle.text.length < 1) {
ApiResponseData apiResponseData = ApiResponseData(
responseCode: "17", responseMsg: "Event title is required.");
return apiResponseData;
}
if (eventString.text.length < 1) {
ApiResponseData apiResponseData = ApiResponseData(
responseCode: "17", responseMsg: "Event description is required.");
return apiResponseData;
}
Map data = {
"Token": token,
"API": "AddEventToCalender",
"Data": {
"tokenType": "jwt",
"date": date,
"title": eventTitle.text,
"event": eventString.text,
"time": time,
"eventDateEpocMilisecond": eventDateEpocMilisecond
}
};
if (previousEventDocID.length > 10) {
data = {
"Token": token,
"API": "AddEventToCalender",
"Data": {
"tokenType": "jwt",
"date": date,
"title": eventTitle.text,
"event": eventString.text,
"time": time,
"eventDateEpocMilisecond": eventDateEpocMilisecond,
"previousEventDocID": previousEventDocID,
}
};
}
//encode Map to JSON
var body = json.encode(data);
var response = await http.post(Uri.parse(url),
headers: {"Content-Type": "application/json"}, body: body);
if (response.statusCode == 200) {
var result = json.decode(response.body.toString());
if (result['ResponseCode'] == "0") {
/*ApiResponseData(
responseCode: "17", responseMsg: 'Event added to calender.');
return apiResponseData; */
} else if (result['ResponseCode'] == "1") {
apiResponseData.responseCode = result['ResponseCode'].toString();
apiResponseData.responseMsg = result['ResponseMsg'].toString();
return apiResponseData;
}
}
return apiResponseData;
}
}
2nd code for call api_addEvent.dart
Future<void> _addEventToCalender(String date, String time,
int eventDateEpocMilisecond, String previousEventDocID) async {
setState(() {
_progressBarActive = true;
});
var result = await ApiAddEventToCalender().addEventToCalender(
widget.token, date, time, previousEventDocID, eventDateEpocMilisecond);
if (result.responseCode == "0") {
} else {
if (result.responseCode == "1") {
Navigator.of(context).pushNamedAndRemoveUntil(
'/social_signin', (Route<dynamic> route) => false);
} else {
showMessageDialogBox(context, result.responseMsg.toString());
}
}
setState(() {
_progressBarActive = false;
});
}
I want to ask how to fix this error message. I tried to fix it but still had no success. For example ApiResponseData (
responseCode: "17", responseMsg: "Event title is required."); will appear the message "Event title is required." if I do not enter a title. But for unknown errors, I'm not sure I should always show near this page. Can someone help me?
I'm having an issue connecting to a GraphQL endpoint using Web-sockets.
The issues are noted in the comments. I cannot get this working. It works on the browser (separate test application) so the server is fine.
IOWebSocketChannel? _channel;
StreamSubscription? _getSubscription;
connectToWebsocket(BuildContext context) {
// Nothing to listen to. Auth users only.
final auth = authProviderRead(context);
if (auth.modelUser == null) {
return;
}
_channel?.sink.close();
_getSubscription?.cancel();
final headers = {
"Authorization": auth.jwt ?? "",
"Content-Type": "application/json",
};
_channel = IOWebSocketChannel.connect(
Uri.parse(getWebStockUrl()),
headers: headers,
protocols: ["graphql-ws"],
);
// Fails: Just fires "onDone"
// _channel?.sink.add(jsonEncode({"data": subscriptionQuery}));
// Fails with {"type":"connection_error","payload":{"message":"Cannot read properties of undefined (reading 'Authorization')"}}
// _channel?.sink.add(json.encode({"type": "connection_init"}));
// Fails with {"type":"error","payload":{"message":"Invalid message type!"}}
// _channel?.sink.add(jsonEncode(
// {
// "type": "data",
// "query": subscriptionQuery,
// },
// ));
_getSubscription = _channel!.stream.listen((message) {
// Is never fired?
if (kDebugMode) {
print("Got live message");
print(message);
}
// channel!.sink.add('received!');
// channel!.sink.close();
})
..onData((data) {
if (kDebugMode) {
print("onData - WebSocket");
print(data);
}
})
..onDone(() {
if (kDebugMode) {
print("onDone - WebSocket");
}
})
..onError((e) {
if (kDebugMode) {
print("onError - WebSocket");
print(e);
}
});
}
const subscriptionQuery = r'''
subscription Subscription {
gotChatMessage {
messageResults {
message {
markdown
}
}
}
}
''';
I figure it out, there are some additional things that it requires.
From https://github.com/apollographql/subscriptions-transport-ws/blob/master/src/message-types.ts
_channel?.sink.add(jsonEncode({
"type": "connection_init",
"payload": {"Authorization": auth.jwt}
}));
_channel?.sink.add(jsonEncode({
"type": "start",
"payload": {"query": subscriptionQuery}
}));
When users upload a photo in my flutter app I want to call the function below to flag inappropriate images. I first upload the image to firebase storage then call this function using the generated image URL. For now, I just want it to print the results to make sure it works but nothing is printed.
static void isAppropriate(String url) async {
const String safeSearchURl =
"https://vision.googleapis.com/v1/images:annotate";
const apiKey = "HIDDEN";
var headers = {
'Content-Type': 'application/json',
'Authorization': 'key=$apiKey'
};
var request = http.Request('POST', Uri.parse(safeSearchURl));
request.body = '''
{
"requests": [
{
"image": {
"source": {
"imageUri": "$url"
}
},
"features": [
{
"type": "SAFE_SEARCH_DETECTION"
}
]
}
]
}''';
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
} else {
print(response.reasonPhrase);
}
}
}
This is an example of what the printed response should be:
{
"responses": [
{
"safeSearchAnnotation": {
"adult": "UNLIKELY",
"spoof": "VERY_UNLIKELY",
"medical": "VERY_UNLIKELY",
"violence": "LIKELY",
"racy": "POSSIBLE"
}
}
]
}
I have set of data, with some details,when i try to display the the one value returns null,other 2 data is fine,but if i try to show other data it's shows null,if i try to add that to setState,everything become null,There is no problem when i get the "Description","imagepath" i can show it, but the data from the replys object doesn't show
JSON
{
"doc": {
"image": {
"Description": "tested",
"replay": " ",
"Image_Rating": 0,
"replay_status": 0,
"Report_Date": "1591228800",
"Status": 1,
"_id": "5ed88ae73025a4445568ece3",
"image_path": "http://xxx.xxx.xxx.xxx:xxx/area_images/1670281356001.jpg",
"Created_User_Id": "5ed22c2507a33e2c1cf3a3a5",
"Branch_Id": "5ed22bf807a33e2c1cf3a3a4",
"image_temp_path": "http://xxx.xxx.xxx.xxx:xxx/area_images_temp/1670281356001.jpg",
"Order_Id": 32425,
"reg_date": "1591249638163",
"Area_Id": "5dc11c4046c214298f85e2e0",
"Section_Id": "5dc1097546c214298f85e2ae",
"Report_Time_Type": 1,
"mapperId": "5ed22c4207a33e2c1cf3a3a6",
"Created_At": "Thursday, June 4th, 2020, 11:17:18 AM",
"__v": 0
},
"replays": [
{
"replay": "Good\n",
"Report_Date": "1590796800",
"_id": "5ed248e0c1a47a3e8c4ce8bb"
}
]
}
}
Code
Future<String> getImageView(String imageid) async {
Future token = SharedPrefrence().getToken();
token.then((data) async {
var token = data;
var response = await http.post(Urls.Image_Details,
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer $token",
},
body: json.encode({
"imageId": imageid,
}));
if (response.statusCode == 200) {
try {
var resp = response.body;
Map<String, dynamic> value = json.decode(resp);
var name = value['doc']['image'];
Description = name["Description"].toString();
image_path = name["image_path"].toString();
replay = name["replays"]["replay"].toString();
setState(() {
Description = name["Description"].toString();
image_path = name["image_path"].toString();
// replay = name["replays"]["replay"].toString();
});
} catch (e) {
e.toString();
}
}
});
}
"replays" is an array. Try this: name["replays"][0]["replay"].toString()
By adding [0] it will get your first object from that array.
EDIT:
After looking at your json some more I see that name is the wrong object.
"replays" is a member of "doc" not of "image".
I think this should work:
replay = value['doc']["replays"][0]["replay"].toString();
The problem is
"replays": [
{
"replay": "Good\n",
"Report_Date": "1590796800",
"_id": "5ed248e0c1a47a3e8c4ce8bb"
}
]
This is a List of Maps. So as we access the first element in the list you should use
replay= value['doc']["replays"][0]["replay"].toString();
that is the zeroth element of the list.