0
votes

when I try to decode the json it gives me error.

my model class

class States{
  String name;
  String abbreviation;
  States({this.name, this.abbreviation});

  factory States.fromJson(Map<String,String> json){
    return States(
      name: json['name'],
      abbreviation: json['abbreviation']
    );
  }
}

function where I'm using it

Future<void> search(String text) async {
    String jsonString = await loadData();
    var data = jsonDecode(jsonString);

    var states = States.fromJson(data);//here it gives me error

    if (textEditingController.text == null ||
        textEditingController.text.isEmpty) {
      streamController.add(null);
      return;
    } else {
      print(text);
      streamController.add(states.name.startsWith(text.toLowerCase()));
    }
  }

the json data

[
    {
        "name": "Alabama",
        "abbreviation": "AL"
    },
    {
        "name": "Alaska",
        "abbreviation": "AK"
    },
]
1

1 Answers

0
votes

You're passing List<Map> where your parameter is Map<String,dynamic>.

[
    {
        "name": "Alabama",
        "abbreviation": "AL"
    },
    {
        "name": "Alaska",
        "abbreviation": "AK"
    },
]

Do this :

 List<State> states = data.forEach((value) {
   States.fromJson(value);
  });

This way you'll get a list of States, created using your list of response.