Eroor : Type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>' in type cast

21,896

You have a couple of issues...

You should probably tidy up fetch by making it async:

Future<Map<String, dynamic>> fetch() async {
  http.Response response = await http.get('http://10.0.2.2:8000/api/membres');
  if (response.statusCode != 200) return null;
  return json.decode(response.body);
}

If you look at the json you get in postman, you see that the top item is a map - with at least one key membres. That key seems to contain a list of other maps. It looks from your type that you expect to get that list.

If that assumption is correct you could adapt it as follows:

Future<List<Map<String, dynamic>>> fetch() async {
  http.Response response = await http.get('http://10.0.2.2:8000/api/membres');
  if (response.statusCode != 200) return null;
  return List<Map<String, dynamic>>.from(json.decode(response.body)['membre']);
}
Share:
21,896
Yoss
Author by

Yoss

Updated on July 09, 2022

Comments

  • Yoss
    Yoss almost 2 years

    I am new to Flutter, I try to fetch data from my api on "10.0.2.2:8000/api/membres" but got error like type List dynamic is not a subtype of type 'List. I'm following the example of flutter: https://flutter.dev/docs/cookbook/networking/fetch-data#complete-example

    Please help me to follow a helpful tutorial and tell me how to fix this code.

    MyHomePage.dart

    import 'package:flutter/material.dart';
    import 'dart:async';
    import 'package:http/http.dart' as http;
    import 'dart:convert';
    
    class MyHomePage extends StatefulWidget {
      const MyHomePage({Key key}) : super(key: key);
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
    
      static const url = "10.0.2.2:8000/api/membres";
    
      Future<List<Map<String, dynamic>>> _future;
      @override
      void initState() {
        super.initState();
        _future = fetch();
      }
    
      Future<List<Map<String, dynamic>>> fetch() {
        return http
            .get("http://10.0.2.2:8000/api/membres")
            .then((response) {
              return response.statusCode == 200
                  ? response.body
                  : throw 'Error when getting data';
            })
            .then((body) => json.decode(body)) //
            .then((list) => (list as List).cast<Map<String, dynamic>>());
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Home'),
          ),
          body: RefreshIndicator(
            onRefresh: () async {
              _future = fetch();
              setState(() {});
              return _future;
              },
            child: FutureBuilder<List<Map<String, dynamic>>>(
              future: _future,
              builder: (context, snapshot) {
                if (snapshot.hasError) {
                  return Center(
                    child: Container(
                      constraints: BoxConstraints.expand(),
                      child: SingleChildScrollView(
                        physics: AlwaysScrollableScrollPhysics(),
                        child: Text(snapshot.error.toString()),),),);}
                if (!snapshot.hasData) {
                  return Center(
                    child: CircularProgressIndicator(),
                  );}
                return ListView.builder(
                  itemCount: snapshot.data.length,
                  itemBuilder: (BuildContext context, int index) {
                    final item = snapshot.data[index];
                    return ListTile(
                      title: Text(item['nom']),
                      subtitle: Text(item['prenom']),
                    );
                  },
                );
              },
            ),
          ),
        );
      }
    }
    

    I tested the API with Postman and it works :

    enter image description here

    And this is the error : enter image description here

    In the emulator :

    enter image description here

  • Yoss
    Yoss almost 5 years
    OMG, finally it works thank you alooooot, But can you explain to me this part of code above and what was the issue please ?
  • Richard Heap
    Richard Heap almost 5 years
    Basically, anything in JSON is either a map (object in json spec), a list (array in json spec) or a value. When you call json.decode you get back something that might be a List or it might be a Map depending on the contents of the json. As you walk through/down the decoded map/list you find more such dynamic things that might be one or the other. Your json definitely had a map at the top, which had a list as its value. You get its value by indexing by the key ['keyName'] but that gives you a List<dynamic> which you can convert with List<T>.from
  • Richard Heap
    Richard Heap almost 5 years
    You were trying to jamb the top level map coming from your json into a list, but it's not a list, it's a map. It's member membre is a list. (No pun intended: member/membre !)
  • Yoss
    Yoss almost 5 years
    Okey that's clear ,you mean when there is a key like " membre" i need to use map and then i use the list ?
  • Richard Heap
    Richard Heap almost 5 years
    Yes, if your json text says something like: {"membre":[{"id":"56"},{"id":"57"}]} as it does in this case
  • Nirmala Sudhir
    Nirmala Sudhir over 3 years
    @RichardHeap: I was wondering around how to solve this error "Type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>' in type cast" for a long time. You saved my day . Thank you Richard :)