This code seemed to work a month ago but when I returned to coding this today it shows an error.
I have no problem with my back-end as I checked it.
The code below returns:
'Unhandled Exception: type 'List' is not a subtype of type 'Map'
Map data;
List userData;
Future getItems() async {
http.Response response = await http.get("http://172.16.46.130/olstore_serv/get_items");
data = json.decode(response.body);
setState(() {
userData = data["item"];
});
}
Related
What I want to do is get the json from API and make the buttons from the json content.
API response doesn't change, so I want to call this just one time.( not need to recall when reloading the widget)
So, my idea is simply call the API from initState
Future<List> getSmartTags() async {
var url = Uri.parse("http://localhost:8008/api/smarttags/");
var resp = await http.get(url);
return json.decode(resp.body);
}
and want to confirm json is correctly returned.
void initState() {
super.initState();
var temp = getSmartTags();
print(temp);
}
This error occurs.
[VERBOSE-2:ui_dart_state.cc(198)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'FutureOr<List<dynamic>>'
#0 _SmartTagState.getSmartTags (package:flutter_aic/main.dart:64:17)
I think this is the basic concept of Future though, I didn't get it.
I think you're getting back a Map<String, dynamic> whenever you decode your html body with json, and not a List.
Furthermore, your return value is not a Future because of the await. Whenever the request is done, the final value is stored in your variable resp.
So, theoretically, it should work like this:
Map<String, dynamic> getSmartTags() async {
var url = Uri.parse("http://localhost:8008/api/smarttags/");
var resp = await http.get(url);
return json.decode(resp.body);
It would return a Future<Map<String, dynamic>> instead, when you write it without the wait.
And to avoid more errors because of your async function and the print() outside, I would recommend you to print the JSON output inside your function, not in initState.
when I want to get a value from a json form in flutter, i face this error it says
type 'String' is not a subtype of type 'int' of 'index'
and Im using http: ^0.13.4
and this is my code
void getData() async{
Response res=await get("https://something.com");
String dat=res.body;
var datta=jsonDecode(dat)['title'];
print(datta);
}
how can I fix this problem?
dont forget to write Uri.parse
void getData() async{
Response res=await get(Uri.parse("https://something.com"));
String dat=res.body;
var datta=jsonDecode(dat)['title'];
print(datta);
}
You should handle the request in this way, worked for me:
void getData() async {
String baseUrl = "something.com";
String endpoint = "/your/endpoint";
Uri url = Uri.https(baseUrl, endpoint, {});
http.Response response = await http.get(url);
// Error handling
// if (response.statusCode != "200") {
// sendError();
// }
String stringBody = response.body;
}
Then you convert the string into a JSON object using dart:convert library:
import "dart:convert";
// Json object
Map<String, dynamic> jsonVar = json.decode(stringBody) as Map<String, dynamic>;
That should be enough, but I suggest you to implement a model class to handle your response, and another model to handle the kind of object you are working with (e.g. Book, Post, Product, etc).
Do we have to use different google map API keys for each iOS, android, and place autocomplete?
currently, I am using one API key for all like this
and something is not working. the map suggests me the name of the locations when I type in the search text field, but I get the error when I tap on the name of the location. the error says
Unhandled Exception: type 'Null' is not a subtype of type 'Map<String, dynamic>' in typecast
I think I am doing something wrong with the API keys.
Do we have to use different keys for each platform?
here is my http request
Future<String> getPlaceId(String input) async {
final String url =
'https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=$input&inputtype=textquery&key=$autocompletekey';
final response = await http.get(Uri.parse(url));
var json = convert.jsonDecode(response.body);
var placeId = json['candidates'][0]['place_id'] as String;
print(placeId);
return placeId;
}
Future<Map<String, dynamic>> getPlace(String input) async {
final placeId = await getPlaceId(input);
final String url =
'https://maps.googleapis.com/maps/api/place/findplacefromtext/json?place_id=$placeId&key=$autocompletekey';
final response = await http.get(Uri.parse(url));
var json = convert.jsonDecode(response.body);
var results = json['result'] as Map<String, dynamic>; // this line of code produces error
print(results);
return results;
}
I'm trying to fetch some posts from my RESTAPI using the provider package and either_options but I'm having some troubles. Every time I'm running the app it gives me this error
type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List'
this is where it mentions the error:
Future<Either<String, List<Post>>> getPostsList() async {
var url = Uri.tryParse("myUrl");
try {
var response = await http.get(url);
final List responseBody = jsonDecode(response.body);
return Right(PostsList.fromJson(responseBody).postsLists);
} catch (e) {
print(e);
return Left(ApiErrorHandling.getDioException(e));
}
}
Also Here:
List<Post> postsList = List<Post>();
getPostsList() async {
final Either<String, List<Post>> result =
await ApiServices().getPostsList();
result.fold((e) {
setErrorMessage(e);
setUiStateAndNotify(UISTATE.ERROR);
}, (f) {
postsList = f;
setUiStateAndNotify(UISTATE.SUCCESS);
});
}
I'm really confused as to why this error shows so I would like to know why. thanks
I opened your api result, the list you are interested in is located at the key "data" in response body, so change your code to this:
final List responseBody = jsonDecode(response.body)["data"];
I want to use CoinMarketCap API in flutter. But where I want to add data from map to list, an error will occur which says:
type 'string' is not a subtype of type 'int' of 'index'.
here's my code, I used this tutorial Migrating to the new CoinMarketCap API with Flutter
Future<void> getCryptoPrices() async{
List cryptoDatas = [];
print('Crypto Prices are Loading...');
String apiURL= "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest";
http.Response response = await http.get(apiURL, headers: {'X-CMC_PRO_API_KEY': 'api code'});
Map<String, dynamic> responseJSON = json.decode(response.body);
if (responseJSON["status"]["error_code"] == 0) {
for (int i = 1; i <= responseJSON["data"].length; i++) {
cryptoDatas.add(responseJSON["data"][i.toString()]); // THE ERROR WILL HAPPEND HERE
}
}
setState(() {
this.cryptoList = cryptoDatas;
print(cryptoList);
});
Thank you in advance.
I had this same problem today, and I fixed it with this code. The code is a little different from yours but should do the same thing. If it didn't work then let me know.
Future<String> getCryptoPrices() async {
// API URL
var response = await http.get(
Uri.parse("API URL"),
// Only Accepts data in the formate of json
headers: {
"Accept": "application/json",
});
// this gets the data from the json
var first = json.decode(response.body);
//this is optional if you want to filter through the data
var second = first['current'];
var third = second['temp'];
// this prints out the data from the json
setState(() {
print(third);
});
}
change this line
cryptoDatas.add(responseJSON["data"][i.toString()])
to:
cryptoDatas.add(responseJSON["data"][i])