Flutter run -d chrome not fetch json url - json

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

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

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

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 json data from http.get is returning old database values in App and Latest values in Browser

final String url = "https://stsrefiners.com/wp-content/plugins/calculator/templates/mobilefixedval.php";
List data;
void initState()
{
super.initState();
//this.getJsonData();
Timer.periodic(Duration(seconds: 10), (timer) {
this.getJsonData();
});
}
Future<String> getJsonData() async
{
var response = await http.get(
Uri.encodeFull(url),
headers: {"Accept":"application/json"}
);
setState(() {
var convertDataToJson = json.decode(response.body);
data = convertDataToJson;
print(data);
_isLoading = true;
});
return "Success";
}
Data is fetched using the getJsonData Fucntion and in URL the data is fetched using the MYSQL database using mysqli method when I open the URL in browser it returns the latest values but when I fetch the data in application both in android and IOS it returns the old.
The data is not updating at run time
I'm also facing the same issue due to the Network cache setting in the browser.
Workaround solution
I added random URL query value in API call..
For Example:
my actual API URL
www.xyz.com?id=1
I changed this into
www.xyz.com?id=1&r=somerandomnumber (every call)

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