Search code examples
flutterexceptioncastingiterableunhandled

type 'List<dynamic>' is not a subtype of type 'Iterable<Map<String, dynamic>>' in type cast


I am trying to solve this issue that come up after every time I pull down to refresh. The issue message "Unhandled Exception: type 'List' is not a subtype of type 'Iterable<Map<String, dynamic>>' in type cast". As you can see in the pictures uploaded the error message in terminal and the function code. How can I solve it?

enter image description here

enter image description here

Code here

@override
  void initState() {
    super.initState();
    apiNewsPage.getNewsArticles().then((res) {
      setState(() {
        articles = res!;
        _newsArticles.addAll(articles.cast<Map<String, dynamic>>());
      });
    });
  }

  Future<void> refreshList() async {
    List? articles = await apiNewsPage.getNewsArticles(refresh: true);
    setState(() {
      _newsArticles.clear();
      _newsArticles.addAll(articles! as Iterable<Map<String, dynamic>>);
    });
  } ```

Solution

  • There is type mismatch with List<dynamic>, so you have to cast every item in the list.

    Try with following code

    @override
      void initState() {
        super.initState();
        apiNewsPage.getNewsArticles().then((res) {
          setState(() {
            articles = res!;
            _newsArticles.addAll(articles.cast<Map<String, dynamic>>());
          });
        });
      }
    
      Future<void> refreshList() async {
        List? articles = await apiNewsPage.getNewsArticles(refresh: true);
        setState(() {
          _newsArticles.clear();
          _newsArticles.addAll(articles!.cast<Map<String, dynamic>>();//Here is a change
        });
      }