Flutter error: ChromeProxyService: Failed to evaluate expression 'reasonPhrase' - flutter

I am making a flutter app that can request a post or get on a website it works on google website but not on mine.
I tried this example from pub dev
Future<void> sendPost(String path, String hashMap) async {
switch (hashMap) {
case 'getArtifactData':
var url = Uri.https(
'www.googleapis.com', '/books/v1/volumes', {'q': '{http}'});
var response = await http.get(url);
if (response.statusCode == 200) {
setState(() {
_scanBarcode = response.body;
});
} else {
_scanBarcode = 'Response status: ${response.statusCode}';
}
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
break;
default:
null;
}
}
but when I change the url, path, and body it doesn't work.
Future<void> sendPost(String path, String hashMap) async {
switch (hashMap) {
case 'getArtifactData':
var url = Uri.https(
'trivia.lifeupps.com', '/scripts/get_artifact_data', {'id': '1'});
var response = await http.get(url);
if (response.statusCode == 200) {
setState(() {
_scanBarcode = response.body;
});
} else {
_scanBarcode = 'Response status: ${response.statusCode}';
}
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
break;
default:
null;
}
}

I solve the problem. It's because I'm trying to access the source thru another website (different IP/server) when debugging in a browser. meaning a should enable cross-origin resource thru header on PHP.

Related

Flutter upload image

Get Api Flutter dont working
I tried various methods, if the link is wrong, then it should at least be displayed json text in terminal
photo should be shown
Future<dynamic> getPhotoUrl(int profileID) async {
print("get Photo url $profileID");
var client = http.Client();
var url = Uri.parse("$profileBaseUrl/api/v2/profiles/$profileID/photos");
Map<String, String> headers = {
'APIVersion': '1',
"Authorization": token,
};
var response = await client.get(url, headers: headers);
if (200 == response.statusCode) {
return response.body;
} else {
}
print("avatar url: $currentPhotoUrl");
}
tried this and it doesn't work
Future<void> getPhotoUrl(int profileID) async {
print("get photo url $profileID");
var client = http.Client();
Map<String, String> headers = {
"Authorization": token
};
final http.Response response = await client.get(
Uri.parse("$profileBaseUrl/api/v2/profiles/$profileID/photos"),
headers: headers);
if (response.statusCode == 200) {
Map responseBody = jsonDecode(response.body);
var data = responseBody["data"];
if (data.length < 1) {}
else {
currentPhotoUrl.value = data[0]["content"][0]["medium"];
}
} else {
throw WebSocketException("server error: ${response.statusCode}");
}
print("photos url: $currentPhotoUrl");
}

How to get part from JSON using 'response.stream.bytesToString()' instead of "(response.body) ['data']"

Edit 1:
I am new to Flutter, and coding altogether, so please answer in simple terms.
I can get a JSON string from this API: [https://reqres.in/api/users?page=1][1]. using jsonDecode(response.body)
And I can also get specific part within this JSON using
jsonDecode(response.body)['data'] // 'data' is a List[]
But Postman, generates this completely different code to get data from api.
Postman uses response.stream.bytesToString());
Now I want to keep using Postman's auto generated code, but tweek it such that I get only the List, 'data', from the API.
My full code is:
class ApiService {
Future<List<UserModel>> getData() async {
try{
Response response = await get( Uri.parse('https://reqres.in/api/users?page=2'));
List result = await jsonDecode(response.body)['data'];
if (response.statusCode == 200) {
print(response);
print('');
print(response.body);
print('');
print(result);
print('');
return result.map((e) => UserModel.fromJson(e)).toList();
}
else {
print(response.reasonPhrase);
throw Exception(response.reasonPhrase);
}
} catch(e){
print('Error AA gaya \n\n\n $e') ;
throw e;
}
}
}
------------
Postman generated code is:
==========================
var request = http.Request('GET', Uri.parse('https://reqres.in/api/users?page=2'));
a
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
}
else {
print(response.reasonPhrase);
}
[1]: https://reqres.in/api/users?page=1
your code is correct but the way you parse is wrong
Future<List<UserModel>> getData() async {
try{
Response response = await get( Uri.parse('https://reqres.in/api/users?page=2'));
if (response.statusCode == 200) {
var jdata = jsonDecode(response.body);
print(response);
print('');
print(response.body);
print('');
print(jdata);
print('');
return jdata['data'].map((e) => UserModel.fromJson(e)).toList();
}
else {
print(response.reasonPhrase);
throw Exception(response.reasonPhrase);
}
} catch(e){
print('Error AA gaya \n\n\n $e') ;
throw e;
}
}

GET api in flutter failing with I/flutter ( 4017): {code: 404, message: HTTP 404 Not Found}

My requirement is need to make get rest api call in flutter.my code is as below
final url = "https://app2.sas.com/uh/device/1890/publicKey";
https://app2.sas.com/ is my base url followed by api end point
should i need to add any certificate for https://app2.sas.com/ to work?
void getPublickey() async {
print('getPublickey');
try {
final response = await http.get(Uri.parse(url));
final jsonData = jsonDecode(response.body);
if (response.statusCode == 200) {
print(jsonData.toString());
} else {}
} catch (err) {
print(err.toString());
}
}
when i hit above api i m getting below response, please let me know any mistake i m doing above?
I/flutter ( 4017): {code: 404, message: HTTP 404 Not Found}
Any help is appreciated
try
Future <void>
instead of void and remove http
Future getPublickey() async {
print('getPublickey');
try {
final response = await get(Uri.parse(url));
final jsonData = jsonDecode(response.body);
if (response.statusCode == 200) {
print(jsonData.toString());
} else {}
} catch (err) {
print(err.toString());
}
}
I don't think the problem is from Flutter. Trying out your URL https://app2.sas.com/uh/device/1890/publicKey returns a 404 too.
You should double-check the URL and make sure the endpoint is correct.
You should probably be returning the string public key:
Future getPublickey() async {
print('getPublickey');
try {
final response = await http.get(Uri.parse(url));
final jsonData = jsonDecode(response.body);
if (response.statusCode == 200) {
print(jsonData.toString());
return jsonData;
} else {
print(response.statusCode);
return null;
}
} catch (err) {
print(err.toString());
return null;
}
}

Flutter How to send Http (post) Request using WorkManager Plugin

Hello Guys any help will be apprecited please,
I am unable to send Http post or get request using workmanager plugin in flutter, any solutions to this would be highly appreciated, thanks
Here is my code
any help will be appreciated
thanks
Workmanager.executeTask((task, inputData) async {
switch (task) {
case fetchBackground:
print('checkStatusnow');
final sharedPref = await SharedPreferences.getInstance();
pendingStat = sharedPref.getBool('pendingStat');
print('pendingStat $pendingStat');
// await initialStat();
String url = 'https://getStat.com/chargeStat';
try {
var param = {
'authorization_code': authoStatCode,
'email': umail,
'amount': StatFare *100,
};
String body= json.encode(param);
var response = await http.Client().post(Uri.parse(url), headers: <String, String>{
'Authorization': StatKey,
'Content-Type': 'application/json',
'Accept': 'application/json'
},body: body,
);
if (response.statusCode == 200) {
print(response.body);
print("Successfull");
final data = jsonDecode(response.body);
print(data);
if (StatFounds == null) {
print("Status Not found");
}
else {
print ('checkForSta');
}
}
else {
print(response.reasonPhrase);
print("not available");
sharedPref.setBool("Stat", true);
}
} catch (e) {
}

fetching the response from API and dealing with the errors / converting Bytestreem to Map in flutter

I am trying to communicate with a PHP backend using API but I can not reach the body of the response.
I got the base code from the postman.
And here is the data of the body response:
I need to reach the message, and the errors to show them in the UI, the problem is response.stream it's type is Bytestreem and I can not convert it to Map
My code:
Future<void> _authenticateUp(String email, String password,
String passwordconfirmation, String username, String name,
{String phonenumber}) async {
var headers = {
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
};
var request = http.MultipartRequest('POST', Uri.parse('$siteUrl/register'));
request.fields.addAll({
'email': email,
'password': password,
'password_confirmation': passwordconfirmation,
'username': username,
'name': name,
'phone_number': phonenumber
});
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
try {
if (response.statusCode == 200) {
await response.stream.bytesToString().then((value) {
print(value);
});
} else {
// here I want to print the message and the errors
}
} catch (e) {
throw e;
}
}
Add this As for Error your statusCode is not 200
try {
if (response.statusCode == 200) {
await response.stream.bytesToString().then((value) {
print(value);
});
} else {
await response.stream.bytesToString().then((value) {
print(value);
var jsonResponse = json.decode(response.body.toString());
var nameError = jsonResponse["errors"]["name"][0];
var emailError = jsonResponse["errors"]["email"][0];
var usernameError = jsonResponse["errors"]["username"][0];
var passwordError = jsonResponse["errors"]["password"][0];
//now can print any print(emailError);
});
}