Home > OS >  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:05-24

Hi I am getting this error Though this error has been asked by multiple people but I cannot seem to address this in my scenario

How do I correct this error I cannot seem to comprehend how to solve this

Here is the code:

child:FutureBuilder<List<Articles>>(
          future: fetchApiData(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return ListView.separated(
                itemBuilder: (context, index) {
                  Articles articles = snapshot.data![index];
                  const SizedBox(height: 150,);
                  return Container(
                    padding: const EdgeInsets.all(10),
                    foregroundDecoration: BoxDecoration(
                      border: Border.all(
                        color: golden,
                        width: 2,
                      ),
                      borderRadius: BorderRadius.circular(5),
                    ),
                    width: 180,
                    height: 139,
                    margin: const EdgeInsets.all(5),
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        image: NetworkImage(articles.urlToImage!),
                        fit: BoxFit.fill,
                      ),
                    ),
                  );
                },
                itemCount: snapshot.data!.length, separatorBuilder: (BuildContext context, int index) {
                return const SizedBox(height: 10,);
              },
              );
            } else if (snapshot.hasError) {
              return Text('${snapshot.error}');
            }
            return const CircularProgressIndicator();
          },
        ),
      ),
       Future<List<Articles>> fetchApiData() async {
    final response = await http
        .get(Uri.parse('https://newsapi.org/v2/top-headlines?country=us&apiKey=dee40e91ae644e9d818dd88498534c71'));

    if (response.statusCode == 200) {
      List<dynamic> list = convert.jsonDecode(response.body);

      List<Articles> api=
      list.map((e) => Articles.fromJson(e)).toList();

      return api;
    } else {
      throw Exception('Failed to load data');
    }
  }
  
  ************ModelClass***********
  
  import 'package:api_rest/source_model.dart';

class Articles {
  Source? source;
  String? author;
  String? title;
  String? description;
  String? url;
  String? urlToImage;
  String? publishedAt;
  String? content;

  Articles(
      {this.source,
        this.author,
        this.title,
        this.description,
        this.url,
        this.urlToImage,
        this.publishedAt,
        this.content});

  Articles.fromJson(Map<String, dynamic> json) {
    source = json['source'] != null ? new Source.fromJson(json['source']) : null;
    author = json['author'];
    title = json['title'];
    description = json['description'];
    url = json['url'];
    urlToImage = json['urlToImage'];
    publishedAt = json['publishedAt'];
    content = json['content'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.source != null) {
      data['source'] = this.source!.toJson();
    }
    data['author'] = this.author;
    data['title'] = this.title;
    data['description'] = this.description;
    data['url'] = this.url;
    data['urlToImage'] = this.urlToImage;
    data['publishedAt'] = this.publishedAt;
    data['content'] = this.content;
    return data;
  }
}

This is a sample API I am using it to learn flutter

The response is OK but cannot get the data

CodePudding user response:

Try this method fetchApiData():

Future<List<Articles>> fetchApiData() async {
    var response = await http.get(Uri.parse('https://newsapi.org/v2/top-headlines?country=us&apiKey=dee40e91ae644e9d818dd88498534c71'));
    if (response.statusCode == 200) {
      var jsonResponse =
      convert.jsonDecode(response.body) as Map<String, dynamic>;
      List<Articles> api =
      (jsonResponse['articles'] as List<dynamic>).map((e) => Articles.fromJson(e)).toList();
      return api;
    } else {
      print('Request failed with status: ${response.statusCode}.');
      return [];
    }
  }

CodePudding user response:

Because your response.body is LinkedHashMap type instead of List type, I have checked your response, you should change

List<dynamic> list = convert.jsonDecode(response.body);

to

List<dynamic> list = convert.jsonDecode(response.body['articles]);
  • Related