Home > Enterprise >  How to set the list of json data in flutter
How to set the list of json data in flutter

Time:02-04

I'm trying to return the items from this api https://api.maisdecristo.com/api/parents/mdcget00_parentkids/48984974812

but always the error:

Unhandled Exception: type 'List' is not a subtype of type 'Map<String, dynamic>'

this my object and model:

  Future<ProdutoModel> getProduto() async {
    try {
      final response = await http.get(Uri.parse(
          "https://api.maisdecristo.com/api/parents/mdcget00_parentkids/48984974812"));
      var res = jsonDecode(response.body);
      print(res);
      _accountListModel = ProdutoModel.fromJson(res);
      var data = res['filhos'] as List;
      setState(() {
        _list =
            data.map<FilhoModel>((json) => FilhoModel.fromJson(json)).toList();
      });
      return _accountListModel;
    } catch (e) {
      rethrow;
    }
  }
class ProdutoModel {
  ProdutoModel({
    required this.phone,
    required this.desperson,
    required this.desemail,
    required this.filhos,
  });

  final String phone;
  final String desperson;
  final String desemail;
  final List<FilhoModel> filhos;

  factory ProdutoModel.fromJson(Map<String, dynamic> json) => ProdutoModel(
        phone: json["phone"],
        desperson: json["desperson"],
        desemail: json["desemail"],
        filhos: List<FilhoModel>.from(
            json["filhos"].map((x) => FilhoModel.fromJson(x))),
      );
}

class FilhoModel {
  FilhoModel({
    required this.age,
    required this.firstname,
    required this.lastname,
  });

  final int age;
  final String firstname;
  final String lastname;

  factory FilhoModel.fromJson(Map<String, dynamic> json) => FilhoModel(
        age: json["age"],
        firstname: json["firstname"],
        lastname: json["lastname"],
      );
}

return this api

CodePudding user response:

You have type conversion issue make sure the types from the api is the same as the model

CodePudding user response:

you can use this website : https://app.quicktype.io
to generate model to any json file without get any erorr and it gets you functions from json and to json

  • Related