0

I have the following structure that is returned from my API. How do I convert it to a dart object?

[
    {
        "stateName": "Alabama",
        "stateAbbr": "AL"
    },
    {
        "stateName": "Alaska",
        "stateAbbr": "AK"
    }
]

Basically, I want to display a flutter dropdown box with the stateName value..

user2570135
  • 2,669
  • 6
  • 50
  • 80
  • 1
    Possible duplicate of [How to convert Response JSON to Object in Flutter?](https://stackoverflow.com/questions/53001839/how-to-convert-response-json-to-object-in-flutter) – Kirill Matrosov Sep 14 '19 at 13:28

2 Answers2

0

It's a list of maps. first make a State class:

class State{
  final String stateName;
  final String stateAbbr;
  State({
    this.stateName,
    this.stateAbbr,
}) ;

  factory State.fromJson(Map<String, dynamic> json){
    return new State(
      id: json['stateName'],
      title: json['stateAbbr'],
    );
  }
}

then list of States:

class StatesList {
  final List<State> States;

  StatesList({
    this.States,
  });

factory StatesList.fromJson(List<dynamic> parsedJson) {

    List<State> States = new List<State>();
States = parsedJson.map((i)=>State.fromJson(i)).toList();
    return new StatesList(
       States: States,
    );
  }

}

for more information read this article

Mo Meshkani
  • 1,556
  • 2
  • 18
  • 27
0
    class State {
  String stateName;
  String stateAbbr;

  State({this.stateName, this.stateAbbr});

  State.fromJson(Map<String, dynamic> json) {
    stateName = json['stateName'];
    stateAbbr = json['stateAbbr'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['stateName'] = this.stateName;
    data['stateAbbr'] = this.stateAbbr;
    return data;
  }
}

use this website [https://javiercbk.github.io/json_to_dart/][1] it can help you to convert any object JSON to Dart class, and after that, you should use List Object of type State.