not able to access json file in flutter api call - flutter

I want to use JSON from this link https://howtodoandroid.com/movielist.json.
This is my code where I want to call API from the above link
Future getMovieList() async {
final response = await http.get(Uri.parse("https://howtodoandroid.com/movielist.json"));
if (response.statusCode == 200) {
allMovielist = jsonDecode(response.body);
}
}
i got error "failed to load response data: no data found for resource with given identifier"

Future<List<YourModel>> getMovieList() async {
final response = await http.get(Uri.parse("https://howtodoandroid.com/movielist.json"));
if (response.statusCode == 200) {
/// On first the data will get is always unassigned or just dynamic
/// which cant be identify
final List<dynamic> list = jsonDecode(response.body);
/// try to print or log the data if the data goes to status 200 and able
/// to see it
log(list.map((e) => e).toList().toString());
/// this one will return the indicate assigned data
return list.map((e)=> YourModel.fromJson(e)).toList();
} else{
return [];
}
}

If you are trying this on the web run this command flutter run -d chrome --web-renderer html
if you still get a CROS error disable the web security.
1- Go to flutter\bin\cache and remove a file named: flutter_tools.stamp
2- Go to flutter\packages\flutter_tools\lib\src\web and open the file chrome.dart.
3- Find '--disable-extensions'
4- Add '--disable-web-security'
I get this answer from this link
or consider this package also
Example Code
Future getMoviesList() async {
var headers = <String, String>{'Content-Type': 'application/json'};
var url = Uri.parse('https://howtodoandroid.com/movielist.json');
var response = await http.get(url, headers: headers);
if (response.statusCode == 200) {
var result = json.decode(response.body);
print(result);
return result;
}
}

Related

How can I fetch and use data with this design in flutter

I have this design, I created it and put the data manually, the question is how can I get the data in the image and it is from this website (https://jsonplaceholder.typicode.com/posts) and display it in the same design
var url = Uri.parse("https://jsonplaceholder.typicode.com/posts");
var response = await http.get(url);
if (response.statusCode == 200) {
var responseJson = jsonDecode(response.body);
responseJson as List;
return responseJson.map((e) => YourModel.fromJson(e)).toList();
}
Firstly, you can paste your JSON in the link below, click convert and get your Dart classes for free.
Secondly, you can copy the result which is named JsonPlaceHolderResponse and create a new file in your project, and paste the result there.
Finally, you can use this code to get your data from defined API:
import 'package:http/http.dart';
Future<JsonPlaceHolderResponse?> getData(String url) async {
final _response = await Client().get(
url
);
if (_response.successResponse) {
final _json = jsonDecode(_response.body);
return JsonPlaceHolderResponse.fromJson(_json);
} else {
return null;
}
return null;
}
extension ResponseExtension on Response {
bool get hasWrongCredentials => statusCode == 422;
bool get tooManyRequests => statusCode == 429;
bool get successResponse => statusCode >= 200 && statusCode < 300;
}

Writing a query parameter with an array of values in Flutter

I'm using the Http package on flutter. I have a query request that should take a large list of values
localhost/accounts/fax-info?ids=(66, 97) this works in post man however. In flutter I tried this exact thing and it just gives me a general error that doesn't tell me anything.
Future<List<CustomerInfo>> getFaxinfo(
List<UnfinishedAccount> accounts,
) async {
final baseUrl = 'localhost';
final int port = 3003;
final accountsPath = '/accounts';
final accountsFaxInfoPath = '$accountsPath/fax-info';
try {
final uri = Uri.parse('http://localhost:3003/accounts/fax-info?ids=(66, 97)');
final response = await http.get(uri, headers: headers);
if (response.statusCode == 200) {
print(jsonDecode(response.body));
}
return [CustomerInfo(sent: 200, received: 300, name: 'Test')];
} catch (err) {
print(err);
rethrow;
}
I tried mapping the values of accounts.id then converting that to a list, I'm not sure if that's the correct way to put it in the query as a list of values because it looks like (66,97) not [66, 97].

Flutter Web - Error code: XML Http Request Error

I am trying to fetch a simple JSON file from my HTTPS server in flutter web however, it doesn't fetch the JSON and simply prints :-
Error code: XMLHTTPRequest error
How do I fix this issue? Here's my code -
Future<List<GamesJSON>> fetch(String link) async {
final res = await get(Uri.parse(link));
if (res.statusCode == 200) {
final data = json.decode(res.body);
final rest = data;
list = rest.map<GamesJSON>((json) => GamesJSON.fromJson(json)).toList()
as List<GamesJSON>;
}
return list;
}
You need to change this line
list = rest.map<GamesJSON>((json) => GamesJSON.fromJson(json)).toList()
as List<GamesJSON>;
to this
List<GamesJSON> list = rest.map<GamesJSON>((json) => GamesJSON.fromJson(json)).toList();

How to fetch string?

I have code like this:
Future<http.Response> makeRequest() async {
return await http.get(Uri.parse(url));
}
my "url" is a string, and it is working. From the internet i got string like "10" or "125", but when i use this method in my project and im converting it to string it only writes me an error:
Instance of 'Future Response'
, how can i take my string from the internet?
this is my url:
https://apialgorytm20210606150610.azurewebsites.net/algorytm/5w5
Future<String> getObjectFromAPI() async {
var response = await http.get(Uri.parse('www.myAPI.com/getData'),); //1
if (response.statusCode == 200) { //2
return(jsonDecode(response.body)["yourObjectHere"]); //3
} else {
return 'error';
}
}
Here you go.
Put your API url in line 1.
Line 2 checks if you receive a 200OK return or some kind of error code. Line 3 prints the decoded JSON response from the API, and you can enter the specific object you want to fetch as well
Future makeRequest() async {
var res= await http.get(Uri.parse(url));
If(res.statusCode==200){
print(res.body);
return res.body;}else{return null;}
}
now use the above function
var data=makeRequest();
print(data);

Unable to use a Future value - Flutter/Dart

I've fetched a json object and deserialized it and then returned it too.
I want to use this in another file.
I'm unable to assign the values that I'm getting in the first step.
Here are all the codes...
Service
Future getGeoPoints(String accessToken, String tripId) async {
String requestUrl;
var response = await get(
Uri.parse(requestUrl),
headers: {
'Authorization': "Bearer $accessToken",
},
);
if (response.statusCode == 200) {
Map<String, dynamic> responseBody = json.decode(response.body);
GetGeoPoints geoPoints = GetGeoPoints.fromJson(responseBody);
List listOfGeoPoints = [];
for (var geoPoint in geoPoints.geoPoints) {
listOfGeoPoints.add(
{
'latitude': geoPoint.latitude,
'longitude': geoPoint.longitude,
'timestamp': geoPoint.timeStamp,
},
);
}
// print('List of geo points: ' + '$listOfGeoPoints');
return listOfGeoPoints;
} else {
throw Exception('Failed to load data from server');
}
}
File where I need the above values
List routeCoordinates;
Future<void> getValues() async {
getGeoPoints(widget.accessToken, widget.tripId)
.then((value) => routeCoordinates = value);
}
When I run the app, routeCoordinates is null but when I hotreload, it contains the value.
I want to have the values as soon as the screen starts. What is the right way to assign the values here?
I've also tried this:
routeCoordinates = getGeoPoints...
It throws error..
Please help.. Thanks..
The function getGeoPoints() is an asynchronous one. But on the other file, you are not using the await keyword, instead you are using then(). So your code is not waiting for that function to return value.
Try using below code,
List routeCoordinates;
Future<void> getValues() async {
routeCoordinates = await getGeoPoints(widget.accessToken, widget.tripId);
}
Let us know how it went.
You need to use a FutureBuilder to define a behaviour depending on the state of the request. You'll be able to tell the widget what to return while your app is waiting for the response to your request. You can also return a specific widget if you get an error(if your user is offline, for example).
Edit: I've linked the official docs but give this article a read if it's not clear enough.