Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'FutureOr<List<dynamic>>' - flutter

Im trying to get json data from the server
here is the code:
void main() async{
List data = await getData();
print(data);
runApp(MyApp());
}
Future<List> getData() async {
String myUrl = "https://dashboard.ssitanas.com/public/api/categories";
http.Response response = await http.get(myUrl, headers: {
'Accept': 'application/json',
});
return json.decode(response.body);
}
what is the problem ?

The response coming from the api is a Map, not a List, but from the looks of things, there seems to be a list inside the map
so just do this :
var res = json.decode(response.body);
var listData = res["data"];
//assuming the list inside the map is called data
return listData;

Related

Flutter Error type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>'

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

Flutter type '_SimpleUri' is not a subtype of type 'String' error

This is my simple code
try{
final dynamic headers = await _getReqHeader();
http.Response res = await http.get(Uri.parse(url), headers: headers);
print("Dres2="+res.toString());
return _result(res);
}catch(e){
print("Dres3="+e.toString());
return _result({});
}
This code works well. But when use some url's I get type '_SimpleUri' is not a subtype of type 'String' error. In postman this url works perfectly. I could not find any information about _SimpleUri. How can I solve this problem?
The get method of the http package takes Uri.https(hostUrl , apiEndpoint) not Uri.parse.
The error appears because a simple URLs being passed to it. To fix this, you have to do this:
http.Response res = await http.get(Uri.https(host, url), headers: headers);
I had a similar issue and that's how I solved it.
static const baseUrl = "apihost.com";
Future<http.Response> _get(String url, {host = baseUrl}) async {
final header = <String, String>{};
return http.get(Uri.https(host, url), headers: header);
}
Future<String?> getData() async {
final response = await _get("/endpoint");
if (isSuccessful(response)) {
final json = jsonDecode(response.body);
} else {
print('GET failed [${response.statusCode}]:
${response.body}');
return null;
}
}

Flutter: trying to use jsonDecode - Error: string is not a subtype of type int of index Error

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

How can I use the returned value of data I got from my shared preference json file as a parameter

how can i use this as my url parameter
userData['UserName']
I have json data in my shared preference file. So I tried to get the username
of the signed in user because I want to use as a parameter to an endpoint.
I can print the username quite ok on the console but when tried to add it
on the link, the statusCode response I get is:
null.
E/flutter ( 906): Receiver: null
E/flutter ( 906): Tried calling: []("UserName")
please how can I extract his username and add it to the endpoint:
Here's the endpoint that shared preference snippet that gives me the
username:
var q;
var userData;
void _getUserInfo() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
var userJson = localStorage.getString('loginRes');
user = json.decode(userJson);
setState(() {
userData = user;
});
print(userData['UserName']);
}
and this is where I want to use it, on the get request link below:
Future<void> get_farmer_eop() async {
final response = await http.get(
'http://api.ergagro.com:112/GenerateFarmersEop?farmerBvn=${widget.result}&dcOid=${widget.dc_result}&agentName=${userData['UserName']}',
headers: _setHeaders());
print('${response.statusCode}popo');
if (response.statusCode == 200) {
final jsonStatus = jsonDecode(response.body);
setState(() {
q = jsonStatus['Eop'];
});
print('trandid');
print('${q['TransId']}kukuk');
} else {
throw Exception();
}
}
_setHeaders() => {
'Content-type': 'application/json',
'Accept': 'application/json',
};
But on the console I print the username and if I tried to hardcode the agentName which is the username parameter example agentName=johndoh it works but when userData['UserName'] I keep getting null please can anyone help me?
If _getUserInfo not returning anything then why to create a separate method, try below code. It should work.
Future<void> get_farmer_eop() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
var userJson = localStorage.getString('loginRes');
user = json.decode(userJson);
final response = await http.get(
'http://api.ergagro.com:112/GenerateFarmersEop?farmerBvn=${widget.result}&dcOid=${widget.dc_result}&agentName=${user['UserName']}',
headers: _setHeaders());
You are using a wrong formatted url, try this instead:
final response = await http.get(
"http://api.ergagro.com:112/GenerateFarmersEop?farmerBvn=${widget.result}&dcOid=${widget.dc_result}&agentName=${userData['UserName']}",
headers: _setHeaders());

Getting this error - type 'Future<dynamic>' is not a subtype of type 'List<dynamic>'

Whenever trying to call future data and trying converting to List, it returns the error
type 'Future' is not a subtype of type 'List'
Tried type-casting, but no help
On HomePage.dart
final getPost = NetworkFile().getPosts();
List posts;
void getPostsList() {
setState(() {
var res = getPost;
posts = res as List<dynamic>;
print(posts);
});
}
On Network.dart
class NetworkFile{
Future<dynamic> getPosts() async {
var response = await http.get('$kBlogURL' + 'posts?_embed');
Iterable resBody = await jsonDecode(response.body.toString());
return resBody;
}
}
You are decoding the response and its a List of type dynamic. There are few method to handle it. You can create a simple PODO class and cast/mapped to it. Or just do like below:
List posts = [];
void getPostsList() async {
final fetchedPosts = await NetworkFile().getPosts();
setState(() {
posts = fetchedPosts;
});
print(posts);
}
Here is a nice article about PODO.
final getPost = NetworkFile().getPosts();
Map posts;
void getPostsList() async {
var res = await getPost;
setState(() {
posts = res as Map<String, dynamic>;
print(posts);
});
}
class NetworkFile {
Future<dynamic> getPosts() async {
var response = await http.get('https://onetechstop.net/wp-json/wp/v2');
var resBody = await jsonDecode(response.body.toString());
return resBody;
}
}