Home > front end >  Flutter error: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of ty
Flutter error: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of ty

Time:10-26

I am trying to fetch News data from an API in JSON format and display it in my app.

News Class:

class News {
  final String title;
  final String desc;
  final String imgURL;
  final String url;

  News(
      {required this.title,
      required this.desc,
      required this.imgURL,
      required this.url});

  factory News.fromJSON(Map<String, dynamic> json) {
    return News(
        title: json["title"],
        desc: json["description"],
        imgURL: json["image_url"],
        url: json["url"]);
  }
}

News object getter:

Future<List<News>>? futureData;
  
  Future<List<News>> getNews() async {
    final response = await http.get(Uri.parse(
        'https://api.stockdata.org/v1/news/all?&filter_entities=true&language=en&api_token=api_token&countries=in'));
    if (response.statusCode == 200) {
      List jsonResponse = json.decode(response.body);
      return jsonResponse.map((data) => News.fromJSON(data)).toList();
    } else {
      throw Exception('Unexpected error occurred!');
    }
  }

FutureBuilder to display in the app:

FutureBuilder<List<News>>(
                future: futureData,
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    print(snapshot);
                    List<News> data = snapshot.requireData;
                    return ListView.builder(
                        itemCount: data.length,
                        itemBuilder: (BuildContext context, int index) {
                          return Container(),
                          );
                        });
                  } else if (snapshot.hasError) {
                    return Text("${snapshot.error}");
                  }
                  // By default show a loading spinner.
                  return Center(child: CircularProgressIndicator());
                }),

I keep getting the error: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List' in type cast

CodePudding user response:

The response you receive from the api is of JsonObject similar to map but in the code you are trying to parse it as a list check how it looks here

your News.fromJSON() is written such that its taking only one object where as the data you are getting is of array.

 factory News.fromJSON(Map<String, dynamic> json) {
return News(
    title: json["title"],
    desc: json["description"],
    imgURL: json["image_url"],
    url: json["url"]);

}

Currently your model class can only take one object not a list. you can go through this

  • Related