im tryin to display data from json api inside my flutter app , My Error :
[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>' in type cast
My Method:
List _loadedAkhbar = [];
Future<void> _fetchData() async {
const apiUrl = 'myapi';
HttpClient client = HttpClient();
client.autoUncompress = true;
final HttpClientRequest request =
await client.getUrl(Uri.parse(apiUrl '/${widget.id}'));
print(apiUrl '/${widget.id}');
request.headers
.set(HttpHeaders.contentTypeHeader, "application/json; charset=UTF-8");
final HttpClientResponse response = await request.close();
final String content = await response.transform(utf8.decoder).join();
Map<String, dynamic> data = jsonDecode(content);
setState(() {
_loadedAkhbar = data as List ;
});
}
@override
void initState() {
super.initState();
_fetchData();
}
Json Format
Any Solution to solve it Please
CodePudding user response:
This line is casting your data to a List, when it's actually a Map:
_loadedAkhbar = data as List; // ERROR
You probably want to change the declaration of _loadedAkhbar
:
Map<String, dynamic>? _loadedAkhbar;
And remove the cast:
_loadedAkhbar = data;
CodePudding user response:
Your api response is Map and your casting your map to List and that cause error, instead of this:
List _loadedAkhbar = [];
Map<String, dynamic> data = jsonDecode(content);
setState(() {
_loadedAkhbar = data as List ;
});
Try this:
Map _loadedAkhbar = {};
setState(() {
_loadedAkhbar = jsonDecode(content);
});