Both urls provides same json data but flutter can only parse one - json

Despite both urls showing the same json data, my code only works with the url "https://5f210aa9daa42f001666535e.mockapi.io/api/products" but the other. Wonder why and been struggling for 3 nights for this:
Future<List<Product>> fetchProducts() async {
const String apiUrl =
"http://10.0.2.2:8000/api/book";
//"https://5f210aa9daa42f001666535e.mockapi.io/api/products";
final response = await http.get(apiUrl);[enter image description here][1]
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
List<Product> products = (json.decode(response.body) as List)
.map((data) => Product.fromJson(data))
.toList();
// Return list of products
return products;
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load');
}

I think, you try this way. Using package: dio
https://pub.dev/packages/dio

Related

Can't manage to fetch data from a second JSON file

I'm trying to use a fetched data from a JSON file to make another fetch on a second screen.
Let's say I have a JSON file that was fetched via www.fruits.com/data. Then one of the fruits has an ID of 1. In order to have more information about this fruit, I have to access another JSON file on www.fruits.com/data/1.
I have both of these fetch functions to access JSON and drag said data:
List<Fruitmodel> parseFruit(String responseBody) {
var list = json.decode(responseBody) as List<dynamic>;
List<Fruitmodel> fruits = list.map((model) => Fruitmodel.fromJson(model)).toList();
return fruits;
}
List<FruitDetails> parseDetails(String responseBody) {
var list = json.decode(responseBody) as List<dynamic>;
List<FruitDetails> fruit_details = list.map((model) => FruitDetails.fromJson(model)).toList();
return fruit_details;
}
Future<List<FruitModel>> fetchFruit() async {
final response = await http.get(Uri.parse('https://fruits.com/data'));
if (response.statusCode == 200){
return compute(parseFruits, response.body);
}
else{
throw Exception('Failed to get fruits.');
}
}
Future<List<FruitDetails>> fetchDetails(int? a) async { //"int a" is to get the fruit's ID
String newUrl = 'https://fruits.com/data/' + a.toString();
final response = await http.get(Uri.parse(newUrl));
if (response.statusCode == 200){
return compute(parseDetails, response.body);
}
else{
throw Exception('Failed to get details.');
}
}
On my homepage, I used the first fetch function (FetchFruit), and managed to make a fruit list with the first JSON file by using Future Builder (snapshots), then my next task is to click on a fruit and show its details.
...
onTap:(){
Navigator.push(context,
new MaterialPageRoute(builder: (context)
=> DetailsPage(snapshot.data[index])));
...
So, on my next page, I'm initializing it with data from the fruit I've chosen. Then, I try to make the other fetch function (fetchDetails) by using said fruit's ID contained on the other JSON.
...
body: Center(
child: FutureBuilder(
future: fetchDetails(this.fruit.id), //Using ID to mount the correct URL
...
But... It doesn't work. I did a condition to tell me that if the snapshot has an error, it prints "Data not available" on the screen, and it does that instead of reading the second JSON file. What should I do for the second fetch to be done correctly?
In resume:
1st JSON file -> ID -> used to access 2nd JSON file -> not working
Try using this
String newUrl = 'https://fruits.com/data/$a';
and make sure the value won't be null.

Flutter web json data not getit

i am new to flutter web but this error is crazy my func to get json data is
#override
Future<List<StoryEntity>> getNewAnimation(int id) async{
print("ali");
return (json.decode(
(await http.Client().get(Uri.parse('https://hekayatname.ir/home/getanimation')))
.body)['list'] as List)
.map(
(e) => StoryEntity(
title: e['fullname'],
imagePath: e['logo_url'],
description: "e['description']",
rating: 1,
galleryImagesPath: [],
id: e['id'],
producer: e['address'],
),
).toList();
}
but i recive nothing in flutter.
in web browser my data is like this just go to this link
https://hekayatname.ir/home/getanimation
i change the code to this
Future<List<StoryEntity>> getNewAnimation(int id) async{
print("1");
final response = await http.Client().get(Uri.parse("https://hekayatname.ir/home/getaudioestory"));
if(response.statusCode == 200){
print("2");
}
else{
print("3");
print(response.statusCode);
}
}
i have nothing to both if and else
if not work,else not work.... need help!!
Visit this link. Copy your json response and paste in the json section. Give your class name and hit Generate Dart.
Now hit copy dart code and add it your project. Then you can use it like inside the success case.
Note if you face any error of Null object. Thats mean your response contains null values and replace this data type with the corresponding data type.
if(response.statusCode == 200){
print('2');
YourJsonResponse obj = YourJsonResponse.fromJson(jsonDecode(response.body));
} else{
print("3");
print(response.statusCode);
}

Flutter - Multiple HTTP Requests to the same JSON

I have this API where go to fetch data.
For each "date" I have a JSON Object.
What I want to do is fetch objects from let's say 5 years and get them on the same final JSON http response.
So I don't have to display only a day at the time.
Future<List<Schedule>> getFromEspnSchedule(String sport) async {
final url = 'http://myserver.com/api/$date'; //the $date would be e.g. 2010, 2011, 2012, ...
final response = await http.get(url);
if (response.statusCode == 200) {
List jsonResponse = json.decode(response.body);
return jsonResponse.map((data) {
return new Schedule.fromJson(data);
}).toList();
}
}
What is the best way to implement this?
If your API returns just a single Schedule object, you need to modify your method to get a single element.
Future<Schedule> getFromEspnSchedule(String sport) async {
final url = 'http://myserver.com/api/$date';
final response = await http.get(url);
if (response.statusCode == 200) {
return Schedule.fromJson(json.decode(response.body));
} else {
// make sure you return API error here
}
}
After you do this, you can go ahead and chain this into multiple calls made at the same time to achieve getting the data faster:
List<Schedule> responseList = await Future.wait([
getFromEspnSchedule('football'),
getFromEspnSchedule('volleyball'),
getFromEspnSchedule('basketball'),
getFromEspnSchedule('chess'),
]);
// responseList objects are listed the same way they are called above.
Schedule footballSchedule = responseList[0];
Schedule volleyballSchedule = responseList[1];
Schedule basketballSchedule = responseList[2];
Schedule chessSchedule = responseList[3];

Flutter run -d chrome not fetch json url

I've create Board List function by fetching json url via flutter
First I've crated into window exe it works properly like this below
But when I want to production via chrome or android
It is not working as this below
This is my code to fetch json url what did I do wrong?
Future<List<Schedule>> fetchBoardList() async {
final response = await http.get('http://192.168.10.109:8888/mcschedule/machine/');
String logResponse = response.statusCode.toString();
if (response.statusCode == 200){
//print('ResponseStatusCode: $logResponse'); // Check Status Code = 200
//print('ResponseBody: ' + response.body); // Read Data in Array
List<dynamic> responseJson = json.decode(response.body);
return responseJson.map((e) => new Schedule.fromJson(e)).toList();
} else {
throw Exception('error :(');
}
}

flutter:how can i received value as same as mysql database?

Hi I am try use mysql database in my flutter app...but till now fetch all data as string..what changes i have to done in my below code to received as data as my database...
in below code verify is a number and i want to received as number till time i received verify as string ....please help me ............
FetchJSON() async {
var Response = await http.get(
"http://192.168.42.107/my_payment/getdata.php",
headers: {"Accept": "application/json"},
);
if (Response.statusCode == 200) {
String responseBody = Response.body;
var responseJSON = json.decode(responseBody);
abc = responseJSON['username'];
verify = responseJSON['verified'];
setState(() {
print('UI Updated');
});
} else {
print('Something went wrong. \nResponse Code : ${Response.statusCode}');
}
}
So essentially you want "strongly typed" data for your http response, you have to define such data yourself. Normally people do something like this:
class MyData {
final String username;
final bool verified; // assume this should be a boolean
MyData.fromJson(dynamic json)
: username = json['username'],
verified = json['verified'] == 1; // assume you get back a number for verified
}
Then you can convert your responseJSON to MyData and carry on from there.