Home > Back-end >  Error listing information with rest API with Flutter
Error listing information with rest API with Flutter

Time:10-02

I'm trying to list information from an API remaining on the screen. I have this method:

late List<MyModel> _listAll; // original list fetched from API
late List<MyModel> _displayList; 
.
.

void _ListTransaction() async {
    
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String token = prefs.getString("userToken") ?? "";

    dynamic data = await http.get(Uri.parse('....'), headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'Authorization': '$token',
    });
    
    List<MyModel> listAll= [];

    for (var u in data) {
      MyModel myModel = MyModel.fromJson(u);
      print(myModel);
      listAll.add(myModel);
    }

    setState(() {
      _listAll = listAll;
      _displayList = _listAll ;
    });
  }

Here I get the error:

_TypeError (type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable')

I also tried this approach:

void _ListTransaction() async {

    SharedPreferences prefs = await SharedPreferences.getInstance();
    String token = prefs.getString("userToken") ?? "";

    dynamic data = await http.get(Uri.parse('....'), headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'Authorization': '$token',
    });

   var list = json.decode(data.body);
    print(list);

    setState(() {
      _listAll = list;
      _displayedList = _petrolList;
    });
    
  }

But here I get the error:

_TypeError (type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List')

You guys could help me with this error. I appreciate any comments!

CodePudding user response:

I think that the error is that _listAll is a type list of the MyModel, but the list in the "setState" method is Map<String, dynamic>.

I hope to help you.

CodePudding user response:

You should do something like this :

var result = json.decode(data.body);
List<Map<String, dynamic>> list = (result as List).map((e) => e as Map<String, dynamic>).toList();
list.forEach((element) {
  _listAll.add(MyModel.fromJson(element));
}

In my case this works because i have a list of Map<String, dynamic> in my result var from my API.

  • Related