I work on a delivery man application and I need to have from an API the details of an order received on the account of a delivery man.
here is an example:
{
"Status": "1",
"Order": {
"deliveryCost": "5.000",
"amount": "38.400",
"total": "43,400",
"hors_remise": "34.560",
"Dishes": [
{
"cartID": "00000",
"dishID": "13548",
"dimensionID": 0,
"title": "Classic 16 pieces trays:",
"ingredient": "10 piece trays + 2 gunkan + 4 shrimp crunchy",
"price": "38.400",
"quantity": "1",
"imagePath": "https://www.monresto.net/test/plats/P_170121112803.jpg",
"Options": []
}
],
and to access of all this information I must specify the "KEY" I had on the postan
my question is how can i add (orderID)?
there is my code :
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:flutter/material.dart';
class datePageClass extends StatefulWidget {
#override
_datePageClassState createState() => _datePageClassState();
}
class _datePageClassState extends State<datePageClass> {
void getData() async {
http.Response response = await http.post(
'https://api/ws/v3/Delivery/orderDetails.php');
if (respo
nse.statusCode == 200) {
String data = response.body;
var cmddetails = jsonDecode(data);
print(cmddetails);
} else {
print(response.statusCode);
}
print('');
}
#override
Widget build(BuildContext context) {
getData();
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.lightBlue,
),
);
}
}
Did you try this?
var response = await http.post('https://www.apiurl.com/ws/v2/details.php', body: {'OrderID': 1209, 'OtherParam': 'value'});
Then in PHP
$OrderID = $_POST["OrderID"];
$OtherParam = $_POST["OtherParam"];
Make sure to sanitize the variables to avoid SQL Injections
And then you can send JSON back to dart/flutter.
Pre-check: Are your sure that this URL expects http-POST not http-GET?
You want to add orderID to the request, right?
If that's the case, first you need to find if API expects this parameter as query parameter or part of the body.
Nevertheless, here are examples for both cases.
String orderDetailsUrl = 'https://www.monresto.net/ws/v3/Delivery/orderDetails.php';
orderID as query parameter:
orderDetailsUrl += "?orderID=FIXME_ORDER_ID";
http.Response response = await http.post(orderDetailsUrl);
orderID as part of request body:
Map<String, dynamic> data = Map()
..putIfAbsent("orderID", () => "FIXME_ORDER_ID")
var body = jsonEncode(data);
http.Response response = await http.post(orderDetailsUrl, headers: {"Content-Type": "application/json"}, body: body);
Related
I use the following class (a separate dart file) to provide API services:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class Services {
static Future<http.Response> login(String username, String password) async {
var url = "https://10.0.2.2:5001/api/Login/LoginSystem";
Map data = {"Username": username, "Password": password};
var body = json.encode(data);
var response = await http.post(Uri.parse(url),
headers: {
"content-type": "application/json",
"accept": "application/json"
},
body: body);
print(response.statusCode);
print(response.body);
return response;
}
}
And I use the following code to call the service function:
onPressed: () {
var response = Services.login("fa2020", "123");
if (response.statusCode == 200) {
showDialog<String>(
context: context,
builder: (BuildContext context) =>
const AlertDialog(
title: Text("ALert"),
content: Text(response.body),
));
}
}
My problem is that I cannot access the response.statusCode and response.body in the last code. How can I fix it?
Use async-await in onPressed callback as Service.login executes in async manner.
onPressed: () async {
var response = await Services.login("fa2020", "123");
// ...
},
I am just starting to learn flutter and would like to know how to access the endpoints of the twitter API for a project I was creating. I wanted to display a tweet at first ( eventually it would be a random tweet generated with a button.)
My code is given below:
import 'package:twitter_api/twitter_api.dart';
import 'package:flutter/material.dart';
void main() {
runApp(Twittwrapp());
}
final _oauth = new twitterApi(
consumerKey: 'consumerkeyhere',
consumerSecret: 'consumersecrethere',
token: 'tokenhere',
tokenSecret: 'tokensecrethere',
);
Future twitterRequest = _oauth.getTwitterRequest(
"GET",
"statuses/user_timeline.json",
options: {
"user_id": "19025957",
"screen_name": "TTCnotices",
"count": "20",
"trim_user": "true",
"tweet_mode": "extended",
},
);
class Twittwrapp extends StatefulWidget{
#override
_Twitte createState() => _Twitte();
}
class _Twitte extends State<Twittwrapp>{
var tweet = await twitterRequest;
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Text(tweet),
),
);
}
}
And the error i get is XMLHTTPREQUEST.
You can try this.
import 'package:http/http.dart' as http;
var response = await http.get(Uri.http('example.com', 'apiPath'), //without https:// http:// or www
headers: <String, String>{
'consumerKey': 'consumerkeyhere',
'consumerSecret': 'consumersecrethere',
'token': 'tokenhere',
'tokenSecret': 'tokensecrethere',
...
}
);
if (response.statusCode == 200) {
// request successful
print(response.body);
getQuestion();
} else {
// request error
print(response.statusCode); // compare this code with https://developer.mozilla.org/en-US/docs/Web/HTTP/Status and find the problem
}
I am wondering if there are faster ways of doing this fetch, the for loop currently takes approx 10s but it's waiting for each fetch to finish before starting on the next one I also tried a forEach loop but then I had issues with the responses array being empty. Is there any smart Dart way of fetching it faster then returning the array to flamingotest
Here is my code!
import 'package:http/http.dart' as http;
import 'dart:convert';
import '../classes/flamingo_test.dart';
import '../classes/convert_wallet.dart' as walletfunc;
import 'package:flutter_settings_screens/flutter_settings_screens.dart';
import '../utilities/assets.dart' as assets; // Object of assets
Future<FlamingoTest> fetchPost() async {
String apiUrl = "xxxxxx";
var responses = [];
for (var mapEntry in assets.assets.entries) {
var wallet = Settings.getValue<String>("user-wallet", "");
print(wallet);
var userWalletSeed = walletfunc.convertWallet(wallet);
print(userWalletSeed);
var body = json.encode({
"jsonrpc": "2.0",
"method": "invokefunction",
"params": [
"4d92194e8d73980dadbadfc1993b2014c9fbd9da",
"checkFLM",
[
{"type": "Hash160", "value": userWalletSeed},
{"type": "Hash160", "value": mapEntry.value}
]
],
"id": 3
});
Map<String, String> headers = {
'Content-type': 'application/json',
'Accept': 'application/json',
};
var response =
await http.post(Uri.parse(apiUrl), body: body, headers: headers);
print(response);
if (response.statusCode == 200) {
print(response);
var uncoded = jsonDecode(response.body);
responses.add(uncoded);
} else {
throw Exception('Failed to load post');
}
}
return new FlamingoTest.fromJson(responses);
}
You can use Future.wait like this. The map will return a Iterable of Future<Response> and perform the post simultaneously.
Future<Response> fetchResponse(var mapEntryValue) async {
//The code in your for-loop goes here
...
return response;
}
Future<FlamingoTest> fetchPost() async {
var responses = [];
await Future.wait(
assets.assets.entries
.map<Future<Response>>(
(MapEntry me) => fetchResponse(me.value),
)
.toList(),
).then((listOfResponses) {
responses.addAll(listOfResponses);
});
return new FlamingoTest.fromJson(responses);
}
I am currently working on an API and I want to post a list of data to the API.
this is an e-commerce example, so I would need to pass the multiple items in the cart as per the line no, line no will auto-increment. and order should be posted with the same order ID but with a different order number.
This is what the Json looks like -
{
"VarFID": 1,
"VarCID": 1,
"VarAreaCode": 1,
"VarAge": 250,
"VarB": 20,
"VarF": 1,
"VarC": 256,
"VarF": 1,
"OrderLines": [
{
"OrderID": "SQ/19/10",
"Line No_": 1,
"Date": "2019-04-02 00:00:00",
"Time": "2019-04-02 11:38:48",
"No_": "FAG-033",
"Name": "LC GOLD",
"Quantity":000,
"Unit Price": 10000,
"Amount": 10000,
"Status": "Under Processing",
"Remarks": "VIKRAM",
"VariantCode":3
},
{
"OrderID": "SQ/19/10",
"Line No_": 2,
"Date": "2019-04-02 00:00:00",
"Time": "2019-04-02 11:38:48",
"No_": "F061",
"Name": "LC S - I",
"Quantity": 00,
"Unit Price": 100,
"Amount": 300,
"Status": "Under Processing",
"Remarks": "VIKRAM ",
"VariantCode":2
}
]
}
This is the code I am using to generate the array, the data is going through, but it is only posting one item/line and not both of them.
void sendData2() async {
mainModel = MainModel(
VarFID: "1",
VarCID: "1",
VarAreaCode: "1",
VarAge: "1",
VarB: "1",
VarF: "1",
VarC: "1",
VarF: "1",
OrderLines: listOrderLines.OrderLines);
var response = await http.post(
Uri.https('softwareonus.com:8082', '/admindealerlist/'),
headers: {"Content-Type": "application/json"},
body: json.encode(mainModel.toJson()),
);
print(" Send Data 2 Response : ${response.body}");
print(" Send Data 2 Response : ${response.statusCode}");
}
I have created model classes using JsonSerialazble
You are doing body: json.encode(mainModel.toJson()), which is pointless since your function .toJson() in your model already does the json.encode(..) for you. You should just .post your mainModel.toJson() to your API.
Based on the data, you have shared. Create 2 Model Classes-
Object Model Class of each object you have
Super Model class (use Object Model Class here like the code)
code Snippet:
ObjectModel-:
import 'package:json_annotation/json_annotation.dart';
part 'ObjectModel.g.dart'; // you have to use naming convention of like this (yourfilename.g.dart)
#JsonSerializable()
class ObjectModel
{
String orderId;
String lineNo;
//All other variable define here
// Initilize all in the constructor
ObjectModel({this.orderId,this.lineNo,[.... your othersVariable...]});
#override
factory ObjectModel.fromJson(Map<String, dynamic> json) =>
_$ObjectModelFromJson(json);
Map<String, dynamic> toJson() => _$ObjectModelToJson(this);
}
SuperModel:
import 'package:json_annotation/json_annotation.dart';
part 'SuperModel.g.dart'; ///you have to use naming convention of like this (yourfilename.g.dart)
#JsonSerializable()
class SuperModel {
String varFid;
String varCID;
// alll othervarialble...
List<ObjectModel> orderLines;
//initilize all in constructor
SuperModel({ this.varFid,this.varCID ,[.....otherVariable],this.orderLines });
factory SuperModel.fromJson(Map<String, dynamic> json) =>
_$SuperModelFromJson(json);
Map<String, dynamic> toJson() => _$SuperModelToJson(this);
}
Note: To create Model Classes I am using this two packages and I have put that in dev_dependency:
dev_dependencies:
flutter_test:
sdk: flutter
build_runner:
json_serializable: ^3.3.0
Now you have to run the below command to generate the g.dart file
flutter pub run build_runner build
Now finally you can do HTTP Post request and model class like this-
void send() async {
\\SuperModel supermodel = SuperModel ([initialize data to this model class])
var response = await http.post(
Uri.https('softwareonus.com:8082', '/admindealerlist/'),
headers: {"Content-type": "application/json"},
body: json.encode(supermodel .toJson()));
print(response.body);
}
}
Alternatively you can watch my Model Class series on Youtube Here is the link: https://youtube.com/playlist?list=PLtIU0BH0pkKpXE-1vC7NswofFPby1OYh-
Thanks :)
Update:
Suppose there is a button in your app, when you click on the button then you add the data on the list
class _ListDataState extends State<ListData> {
SuperModel superModel = SuperModel ();
#override
Widget build(BuildContext context) {
// your UI code
}
void add() {
setState(() {
superModel.orderLines.add(ObjectModel(Your all variable initialize here);
});
}
Call this add method whenever you wanted to add new order in your list. After adding all data send it using send method
void send() async {
var response = await http.post(
Uri.https('softwareonus.com:8082', '/admindealerlist/'),
headers: {"Content-type": "application/json"},
body: json.encode(supermodel .toJson()));
print(response.body);
}
Replace with your object class, which must have the toJson() method that returns the Map.
import 'dart:convert' on to your API function class
And don't forget to add,
headers: {'Content-type': 'application/json','Accept': application/json'},
Future<bool> addToSaleDetail(List<YourCustomObject> _listOfObject) async {
String unparsedUrl = "$baseUrl/AddMobileListSaleBrief";
var url = Uri.parse(unparsedUrl);
List jsonList = [];
_listOfObject.map((item) => jsonList.add(item.toJson())).toList();
final response = await http.post(
url,
body: json.encode({"finalResponse": jsonList}["finalResponse"]),
headers: {
'Content-type': 'application/json',
'Accept': 'application/json'
},
);
if (response.statusCode == 200) {
return true;
} else {
return false;
}
}
Try to change your mainModel to Map<String, dynamic> then encode your Map<String, dynamic> to json and send it to body. Add this 'Content-type': 'application/json' to your headers to make your request sent as json. For Example :
List<Map<String, String>> listItem = <Map<String, String>>[];
for (var element in myList) {
Map<String, String> val = {
'product': element.product.id_product.toString(),
'quantity': element.quantity.toString(),
'total': element.total.toString(),
};
listItem.add(val);
}
Map data = {
'pay': pay,
'customer': id_customer.toString(),
'items': listItem, // this is a List
};
final http.Response response = await client.post(
Uri.parse(...), // your url
headers: {
'content-type': 'application/json' // don't forget this one
},
body: jsonEncode(data), // encode my Map to json
);
That's it! (by the way this is example of my code)
I am trying to send a Json over HTTP post to update a record in my database. I've connected to the server but I'm getting a 415 "Unsupported Media Type" error when I run the request.
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String url = 'http://<Hostname>:
<Port>/jderest/orchestrator/JDE_ORCH_Sample_UpdateMeterReadings_Generic';
Future<String> makeRequest() async {
var response = await http
.post(Uri.encodeFull(url), body: json.encode({
"NewHourMeterReading": "650",
"EquipmentNumber": "34665",
"NewFuelMeterReading": "650"
}), headers: {"Accept": "application/json"});
print(response.body);
}
#override
Widget build(BuildContext context) {
return new Scaffold(
body: new Center(
child: new RaisedButton(
child: new Text('Make Request'),
onPressed: makeRequest,
)));
}
}
Can someone please let me know how to get past this error?
the error that I am facing is this.
I/flutter ( 5881): Unsupported Media Type
Screenshot of Response Headers/Status Code/Body
Sorry for the messy code, it didn't copy paste over every well.
You'll have to add the content-type to your header, setting its value to application/json.
By specifying Accept you're saying that your client is able to understand that response type, not that your request content is of the JSON type.
Basically you're saying "hey there, I'm able to understand JSON, so you can send it to me and I'll be fine with it" but you're not saying "hey I'm going to send you a JSON, be prepared for it!"
For a better understanding, you can find more about Accept here and Content-type here.
You are using incomplete headers for sending the json payload. That is why the server is not accepting you request.
Use the following headers instead:
headers: {
"content-type" : "application/json",
"accept" : "application/json",
},
Send Json and Accept Json using:-
Future<String> addData(Map<String, dynamic> request) async {
final url = 'http_url';
try {
final response = await http.post(url,
headers: {
"content-type" : "application/json",
"accept" : "application/json",
},
body: jsonEncode(request));
final responseData = jsonDecode(response.body) as Map<String,dynamic>;
return responseData['message'];
} catch (error) {
throw error;
}
}