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

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.

Related

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);
}

Depending dropdown data showing Faild assertion error

I need to display list of Lab name in the dropdown list and when I click Lab name it need to go to respective Test of that Lab. I tried with different possible way to achieve this, following approach seems to understandable for me but its showing some kind of Error
The following assertion was thrown building MyHomePage(dirty, state: _MyHomePageState#ec203):
A non-null String must be provided to a Text widget.
'package:flutter/src/widgets/text.dart':
Failed assertion: line 378 pos 10: 'data != null'
//CALLING LAB API HERE
List allLabList;
String _myLab;
String allLabInfoUrl = 'http://myurldjhjhfsf';
Future<String> _getLabList() async {
await http.post(allLabInfoUrl, body: {
}).then((response) {
var data = json.decode(response.body);
// print(data);
setState(() {
allLabList = data['Partner'];
});
});
}
// Get TEST information by API
List testList;
String _myTest;
String allTestInfoUrl ='http://putmyurlhere';
Future<String> _getTestList() async {
await http.post(allTestInfoUrl, body: {
"TestId": _myLab,
}).then((response) {
var data = json.decode(response.body);
setState(() {
testList = data['Data'];
});
});
}
}

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

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

How To display last updated data in JSON string using Flutter

I Have try to display Last Updated Data in JSON String using Flutter
this is first json string
[{"name":"John","leads":"2"},{"name":"Manish","leads":"1"},{"name":"Abhijeet","leads":"1"}]
this is my second Updated json string
[{"name":"John","leads":"2"},{"name":"Manish","leads":"2"},{"name":"Abhijeet","leads":"1"}]
So I would to print or display last updated data is Manish or any other name it is last updated
I used to futurebuilder as well as snapshot please help me.
This is API Call
Future fetchUsers() async {
String url = 'http://example.com/API/dashboardData.php';
var result = await http.get(url);
if (result.statusCode == 200) {
return json.decode(result.body);
} else {
throw Exception('Failed');
}
}
You can search for Manish in the list of maps returned by the API.
final data = [
{"name":"John","leads":"2"},
{"name":"Manish","leads":"2"},
{"name":"Abhijeet","leads":"1"},
];
final manishData = data.firstWhere((map) => map['name'] == 'Manish');
print('Name: ${manishData['name']}');
print('Leads: ${manishData['leads']}');

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];