user_odoo
user_odoo

Reputation: 2358

Flutter - String, dynamic is not a subtype of type List<dynamic>

I'm try to load data from rest api to my app get bellow error:

On emulator get this error:

type '_internalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>'

source:

Future <List<Data>> fetchData() async {
  final response =  await http.get(Uri.https('json-generator.com', 'api/json/get/cqwVqdOFrC?indent=2'));


  if (response.statusCode == 200) {
    List jsonResponse = json.decode(response.body);
    return jsonResponse.map((data) => new Data.fromJson(data)).toList();

  } else {
    throw Exception('Error!');
  }
}

class Data {
  final int empno;
  final String ename;
  final int sal;

  Data({this.empno, this.ename, this.sal});

  factory Data.fromJson(Map<String, dynamic> json) {
    return Data(
      empno: json['empno'],
      ename: json['ename'],
      sal: json['sal']
    );
  }
}

Upvotes: 0

Views: 78

Answers (2)

user15782390
user15782390

Reputation:

I had a similar problem recently with Firestore. What I did in my case is I casted the result from my call as a map. This is the issue I opened: https://stackoverflow.com/a/67774067/15782390.

For your code, could you try this for your fetchData() method:

Future <List<Data>> fetchData() async {
  List<Data> data = [];
  final response =  await http.get(Uri.https('json-generator.com', 'api/json/get/cqwVqdOFrC?indent=2'));


  if (response.statusCode == 200) {
    (response as Map).forEach((element) {
    // I'm not sure what information the data class contains but if you know the parameters that it takes in then add them here. If not then please share your data class.
     data.add(Data(/*enter your data class parameters here*/))
    });
    return data
  } else {
    throw Exception('Error!');
  }
}

I haven't tried the code out myself so if it doesn't work and you are unable to fix it maybe have a look at the question I linked. If that doesn't work either then let me know and I'll fix it for you.

Upvotes: 1

Lakmal Fernando
Lakmal Fernando

Reputation: 1540

Change your code as follows.

Future <List<Data>> fetchData() async {
  final response =  await http.get(Uri.https('json-generator.com', 'api/json/get/cqwVqdOFrC?indent=2'));

     if (response.statusCode == 200) {
        Map<String, dynamic> jsonResponse =json.decode(response.body);
        List<Map<String, dynamic>> itemsList =
      List<Map<String, dynamic>>.from(jsonResponse["items"]);
         return itemsList.map<Data>((data) {
           return Data.fromJson(data);
           }).toList();

  } else {
    throw Exception('Error!');
  }
}

class Data {
  final int empno;
  final String ename;
  final int sal;

  Data({this.empno, this.ename, this.sal});

  factory Data.fromJson(Map<String, dynamic> json) {
    return Data(
      empno: json['empno'],
      ename: json['ename'],
      sal: json['sal']
    );
  }
}

Upvotes: 2

Related Questions