Flutter - Multiple HTTP Requests to the same JSON - 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];

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.

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 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 :(');
}
}

how to store json response locally (sqflite database) in flutter

I did not able to store json response from API in sqflite database but i already parsed json response in list and also i stored similar data in sqflite database.
To stored locally i got success and able to perform CRUD operation and sending it to server, similarly i also able to perform CRUD operation on API data but problem arises on synchronization between local and json data.
the below code id for calling json data
Future<List<Activities>> getData() async {
List<Activities> list;
var res = await http
.post("http://xxxx/get-activity", headers: {
HttpHeaders.authorizationHeader: "Bearer " + _token.toString()
});
if (res.statusCode == 200) {
var data = json.decode(res.body);
var rest = data["data"] as List;
// print(rest);
list = rest.map<Activities>((json) => Activities.fromJson(json)).toList();
// print('okay, ${rest[0]}!');
} else {
print('something error');
}
print("List Size: ${list.length}");
return list;
}
solved
var data = json.decode(res.body);
var activities= data["data"] as List;
for (var activity in activities) {
Activity actData = Activity.fromMap(activity);
batch.insert(actTable, actData.toMap());
}
Solution! Please use this flutter plugin json_store

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.