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

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

Related

Flutter _TypeError (type 'List<dynamic>' is not a subtype of type 'List<TeamID>')

I have calling data from and store in a List which I have defined is a list of model. But still its show error that it's List
My code
class TeamsController with ChangeNotifier {
List<TeamID> teamslist = [];
TeamsController() {
getMyTeams();
}
getMyTeams() async {
var response = await ApiService().getMyCreatedTeams();
if (response != null) {
final databody = json.decode(response);
debugPrint(databody['data'].toString());
teamslist =
databody['data'].map((item) => TeamID.fromJson(item)).toList();
notifyListeners();
}
}
}
Its showing error on teams list that _TypeError (type 'List' is not a subtype of type 'List')
Its working if I first store in list like this
final List list = databody['data'];
teamslist = list.map((item) => TeamID.fromJson(item)).toList();
You can assign your main list as List<dynamic> like this:
class TeamsController with ChangeNotifier {
List<dynamic> teamslist = [];
TeamsController() {
getMyTeams();
}
getMyTeams() async {
var response = await ApiService().getMyCreatedTeams();
if (response != null) {
final databody = json.decode(response);
debugPrint(databody['data'].toString());
teamslist =
databody['data'].map((item) => TeamID.fromJson(item)).toList();
notifyListeners();
}
}
}
That would work but if you want to know the type then you can first check the type and then assign the type to it. You can the type like this:
print(databody['data'].map((item) => TeamID.fromJson(item)).toList().runtimeType);
After that you can assign teamslist to that type.
The code you have shown looks reasonable. Given this
List<TeamID> teamslist = [];
...
teamslist =
databody['data'].map((item) => TeamID.fromJson(item)).toList();
Dart's type inference will type this assignment as you're expecting provided that TeamID.fromJson()'s return type is TeamID.
So please either check your definition of TeamID.fromJson() or post its code in your question.
(Note, there is no compelling reason to use dynamic in this case.)

Getting this error when fetching items in flutter "Error Exception: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>' in type cast"

Getting this error when fetching items from API
"Error Exception: type 'List' is not a subtype of type 'Map<String, dynamic>' in type cast"
class Services {
static Future<List<Products>> getProducts() async {
try {
final response =
await http.get(Uri.parse('http://67.205.140.117/api/products'));
if (response.statusCode == 200) {
List<Products> list = parseProducts(response.body);
return list;
} else {
throw Exception("Error");
}
} catch (e) {
throw Exception(e.toString());
}
}
static List<Products> parseProducts(String responseBody) {
List parsed = (json.decode(responseBody)).cast<Map<String, dynamic>>();
return parsed.map<Products>((json) => Products.fromJson(json)).toList();
}
}
json response
[[{"id":1,"productname":"iPhone","description":"iPhone Xs Max","price":120000,"units":2,"images":"2022061331Untitled design (2).png","category":"1","created_at":"2022-06-07T13:31:25.000000Z","updated_at":"2022-06-07T13:31:25.000000Z"}],"Products Fetched"]
remove .cast<Map<String, dynamic>>(); and change the code to List parsed = (json.decode(responseBody)as List);

How to solve Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String'

String baseUrl = 'https://api.mapbox.com/geocoding/v5/mapbox.places';
String accessToken = dotenv.env['MAPBOX_ACCESS_TOKEN']!;
Dio _dio = Dio();
Future getReverseGeocodingGivenLatLngUsingMapbox(LatLng latLng) async {
String query = '${latLng.longitude},${latLng.latitude}';
String url = '$baseUrl/$query.json?access_token=$accessToken';
url = Uri.parse(url).toString();
print(url);
try {
_dio.options.contentType = Headers.jsonContentType;
final responseData = await _dio.get(url);
return responseData.data;
} catch (e) {
final errorMessage = DioExceptions.fromDioError(e as DioError).toString();
debugPrint(errorMessage);
}
}
Using the above function below
Future<Map> getParsedReverseGeocoding(LatLng latLng) async {
var response =
json.decode(await getReverseGeocodingGivenLatLngUsingMapbox(latLng));
Map feature = response['features'][0];
Map revGeocode = {
'name': feature['text'],
'address': feature['place_name'].split('${feature['text']}, ')[1],
'place': feature['place_name'],
'location': latLng
};
return revGeocode;
}
And then using the above function below:
void initializeLocationAndSave() async {
LatLng currentLocation = getCurrentLatLngFromSharedPrefs();
String currentAddress =
(await getParsedReverseGeocoding(currentLocation))['place'];
}
LatLng getCurrentLatLngFromSharedPrefs() {
return LatLng(sharedPreferences.getDouble('latitude')!,
sharedPreferences.getDouble('longitude')!);
}
However, I am unable to retrieve the currentAddress value. The following error is shown:
Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is
not a subtype of type 'String'
Where I am going wrong? I am using code from here by following the youtube tutorial
Dio does decoding automatically, just remove json.decode.
The default value is JSON, dio will parse response string to json object automatically when the content-type of response is 'application/json'.

_TypeError (type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable<dynamic>') its my error

My api function:
Future<List<User>>fetchData() async {
var response = await http.get(
Uri.parse(link),
headers: headers);
var jsonData = jsonDecode(response.body);
List<User> users = [];
for (var u in jsonData) {
User user = User(u["name"], u["code"], u["id"]);
users.add(user);
}
print(users.length);
return users;
}
im getting this error in for loop. how can i fix it ? i need help. thanks for all
Your data is probably inside a list inside this json response. Look if you have a "data" field in your response, then your for loop would look something like this:
var u in jsonData["data"]
print our your jsonData and let's see.

JSON result not showing in flutter

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