Flutter send data by put request - flutter

I need to put some data thorugh api here is my code
static voteplusQuestion(data, int flag){
print('Api');
print(data);
if( flag == 1 ){
var updateQuestionData = {'Would': data.would, 'Rather': data.rather, 'wouldClick': data.wouldClick, 'ratherClick': data.ratherClick + 1, 'QuestionID': data.QuestionID,};
print(updateQuestionData);
}
if( flag == 0){
var updateQuestionData = {'Would': data.would, 'Rather': data.rather, 'wouldClick': data.wouldClick + 1, 'ratherClick': data.ratherClick, 'QuestionID': data.QuestionID,};
print(updateQuestionData);
}
return http.put(
'https://iv9803zj9d.execute-api.us-east-2.amazonaws.com/Development/would-you-rather',
headers: <String, String>{
'Content-Type': 'application/json',
},
);
}
I need to put updateQuestionData to API but i am not sure how can i do this. Also the print output of updateQuestionData is like this
{Would: Shaving Cream, Rather: Soap, wouldClick: 15, ratherClick: 13, QuestionID: 16563fa7-e833-445f-a76b-a9fbaab3a301}
And the Api is working in code pen like this
var xhr = new XMLHttpRequest();
xhr.open('PUT', 'https://iv9803zj9d.execute-api.us-east-2.amazonaws.com/Development/would-you-rather');
xhr.onreadystatechange = function(event) {
console.log(event);
}
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Authorization', 'allow');
xhr.send(JSON.stringify({Would: "Coffe",Rather: "Tea", wouldClick: 15, ratherClick: 13, QuestionID: "16563fa7-e833-445f-a76b-a9fbaab3a301"}));
I have set the header in function but now dont know how can i set the body

You can send data in a put method as follow:
static voteplusQuestion(data, int flag) async{
var updateQuestionData;
if( flag == 1 ){
updateQuestionData = {'Would': data.would, 'Rather':
data.rather, 'wouldClick': data.wouldClick, 'ratherClick':
data.ratherClick + 1, 'QuestionID': data.QuestionID,};
}
if( flag == 0){
updateQuestionData = {'Would': data.would, 'Rather': data.rather,
'wouldClick': data.wouldClick + 1, 'ratherClick':
data.ratherClick, 'QuestionID': data.QuestionID,};
}
String url = 'https://iv9803zj9d.execute-api.us-east-2.amazonaws.com/Development/would-you-rather';
Map<String, String> headers = {"Content-type": "application/json"};
String data = jsonEncode(updateQuestionData);
// make PUT request
Response response = await put(url, headers: headers, body: data);
// check the status code for the result
int statusCode = response.statusCode;
print(statusCode);
// this API passes back the updated item with the id added
String body = response.body;
print(body);
return body;
}
I am not sure about your use case, but I believe this could be implemented much cleaner.
Note: to use put method or to perform the update operation you need to add the id of the item, I am sure about the url existed in this example

Related

How to change language using uft8 in Flutter

How to change language using uft8 but I tried and couldn't.
Future fetchMos() async {
String mosUrl = ();
var url = Uri.parse(mosUrl);
var headers = {'Client-Token': 'p'};
var response = await client.get(url, headers: headers);
if (response.statusCode == 200) {
var items = json.decode(response.body)['items'];
print(items);
setState(() {
mos = items;
});
} else {
mos = [];
}
}
it looks like the issue is from server side!
check your backend side headers they should support UTF-8
if you're using PHP add this to your connection headers
header('Content-Type: application/json; charset=utf-8');
and if you're using PDO to connect to DB user this array as options
$option = array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES UTF-8"

how create future function in flutter?

i trying to create post function in flutter
here is my code:
Future<String> makePostRequest() async {
String requestResult;
var body = this.toMapRequest();
String requestUrl = RequestZarinpal.PAYMENT_REQUEST_URL;
String gateWayUrl;
String jsonBody = json.encode(body);
final encoding = Encoding.getByName('utf-8');
Response response = await post(
requestUrl,
headers: headers,
body: jsonBody,
encoding: encoding,
).timeout(const Duration(seconds: 10), onTimeout: () {
throw TimeoutException('The connection has timed out, Please try again!');
});
responseBody = response.body;
var parsedJson = json.decode(responseBody);
var data = parsedJson['data'];
var error = parsedJson['errors'];
if (error.toString() != "[]") {
var errorcode = parsedJson['errors']['code'];
print("$body va $requestUrl va $parsedJson");
requestResult = " شما ارور زیر را دریافت کرده اید \n$error";
} else if (data.toString() != "[]") {
var authority = parsedJson['data']['authority'];
requestResult = "اتوریتی شما با موفقیت ساخته شد و به درگاه متصل می شود";
_request.setAuthority(authority);
print(parsedJson);
String gateWay = RequestZarinpal.PAYMENT_GATEWAY_URL;
gateWayUrl = "$gateWay$authority";
if (await canLaunch(gateWayUrl)) {
await launch(
gateWayUrl,
forceSafariVC: false,
forceWebView: false,
headers: headers,
);
} else {
throw 'Could not launch $requestUrl';
}
print(requestResult);
return requestResult;
}
}
but i got this error:
The body might complete normally, causing 'null' to be returned, but the return type is a potentially non-nullable type.
Try adding either a return or a throw statement at the end.dart(body_might_complete_normally)
what should i do?
With the line if (error.toString() != "[]") you divided your function in 2 possibile outcome.
The positive one, doesn't have a return.
Maybe you should move return requestResult; after the curly bracket, so that the return gets fired regardless.
You are missing the return statement inside the if condition
if (error.toString() != "[]") {
var errorcode = parsedJson['errors']['code'];
print("$body va $requestUrl va $parsedJson");
requestResult = " شما ارور زیر را دریافت کرده اید \n$error";
return requestResult;
}

variable doesn't get value from for loop

Why is the Value of Response response not getting the value from the inner for loops response? Its value stays ""
Future getArticle() async {
final data1 = await fetchArticles();
Response response = Response("", 200);
for (int i = 0; i == data1.length; i++) {
response = await get(
Uri.parse('https:/url/' +
data1[i]["file"]),
);
return response; //I want it to have this responses value
}
String data2 = (response.body);
return data2;
}
The for loop you post is like this :
for (int i = 0; i == data1.length; i++) {
response = await get(
Uri.parse('https:/url/' +
data1[i]["file"]),
);
This won't trigger the i++ at all, since you are checking if i == data1.length.
Change it to i < data1.length:
for (int i = 0; i < data1.length; i++) {
response = await get(
Uri.parse('https:/url/' +
data1[i]["file"]),
);
This will make sure it fully loops through the entire length of data1.
This loop doesn't make sense. It will always return the first element and exit the loop in which case you don't need a loop. If you want a loop then do this:
data1.forEach((value) => {
response = await get(
Uri.parse('https:/url/' +
value["file"]),
);
return response.body;
});

for-in using dart Exception: type '_InternalLinkedHashMap<String, dynamic>

i am not familiar using For-in using dart, i use similar code in ts or angular and it work as expected, but get lost when use flutter and need more guidance to use it.
Future<int> datetransaction(String mid) async {
var url = 'http://callsomehttp.com/$mid';
var res = await http.get(url);
if (res.statusCode == 200) {
var dtpoint = json.decode(res.body);
var availabledate = [];
for (var key in dtpoint) {
var dateEle = dtpoint[key]['Balance']['date'];
if (availabledate.indexOf(dateEle) == -1) {
availabledate.add(dateEle);
totalSpending(dateEle, mid);
}
}
print('available data $availabledate');
var spen = totalTransaction.reduce((a, b) => a + b);
return spen ;
} else {
throw Exception(
"Request to $url failed with status ${res.statusCode}: ${res.body}");
}
}
Future totalSpending (String date, String ckey) async {
var total = 0 ;
final String url = 'http://otherurl.com/$date';
final res = await http.get(url);
if (res.statusCode == 200) {
var pdata = json.decode(res.body);
for (var key in pdata) {
var el = pdata[key]['Transaction']['customer_code'];
var ttl = int.parse(pdata[key]['Transaction']['total']);
if( el == ckey) {
totalTransaction.add(ttl);
total = ttl ;
}
}
return total ;
} else {
throw Exception(
"Request to $url failed with status ${res.statusCode}: ${res.body}");
}
}
any guidance to give a light , or other way to get the result really appreciate, thank you

Github api get last Users that committed

I want to get the last users exe. last 100 users that committed on github regardless of repo. I've looked around the github api but can't find the specific api call.
You can use Github Events API and filter PushEvent :
https://api.github.com/events?per_page=100
User(s) who have made the last 100 commits on Github
As a PushEvent may have multiple commits, you will have to sum the size for each PushEvent until you reach 100. Note that you also need to exclude PushEvent with 0 commit. You will also have to manage pagination as you can request 100 events max at once (if one request is not enough to get 100 commits).
An example using nodeJS :
var request = require("request");
const maxCommit = 100;
const accessToken = 'YOUR_ACCESS_TOKEN';
function doRequest(page){
return new Promise(function (resolve, reject) {
request({
url: 'https://api.github.com/events?per_page=100&page=' + page,
headers: {
'User-Agent': 'Some-App',
'Authorization': 'Token ' + accessToken
}
}, function (err, response, body) {
if (!err) {
resolve(body);
} else {
reject(err);
}
});
})
}
async function getEvents() {
var commitCount = 0;
var page = 1;
var users = [];
while (commitCount < maxCommit) {
var body = await doRequest(page);
var data = JSON.parse(body);
var pushEvents = data.filter(it => it.type == 'PushEvent' && it.payload.size > 0);
commitCount += pushEvents.reduce((it1, it2) => it1 + it2.payload.size, 0);
users = users.concat(pushEvents.map(event => ({
login: event.actor.login,
commitCount: event.payload.size
})));
page++;
}
var count = 0;
for (var i = 0; i < users.length; i++) {
count += users[i].commitCount;
if (count >= maxCommit){
users = users.slice(0, i + 1);
break;
}
}
console.log(users);
}
getEvents();
Last 100 Users who have pushed commits on Github
The only things that changes is that we only check that size field is > 0 and build a map for distinct user.
An example using nodeJS :
var request = require("request");
const maxUser = 100;
const accessToken = 'YOUR_ACCESS_TOKEN';
function doRequest(page){
return new Promise(function (resolve, reject) {
request({
url: 'https://api.github.com/events?per_page=100&page=' + page,
headers: {
'User-Agent': 'Some-App',
'Authorization': 'Token ' + accessToken
}
}, function (err, response, body) {
if (!err) {
resolve(body);
} else {
reject(err);
}
});
})
}
async function getEvents() {
var page = 1;
var users = {};
while (Object.keys(users).length < maxUser) {
var body = await doRequest(page);
var data = JSON.parse(body);
var pushEvents = data.filter(it => it.type == 'PushEvent' && it.payload.size > 0);
for (var i = 0; i < pushEvents.length; i++) {
users[pushEvents[i].actor.login] = pushEvents[i].payload.size;
if (Object.keys(users).length == maxUser) { 
break;
}
}
page++;
}
console.log(users);
}
getEvents();