tobias
tobias

Reputation: 91

Flutter convert Map to List for JSON

I am working on a project in Flutter. And I have the problem, that I can´t get all Values from a Map into a List. Is that even possible?

The API I have looks like that:

{
  {
   "adult":false,
   "backdrop_path":"/w41zFKYTsq4wf5QnQJWMXuzWl2F.jpg",
   "title":"Harry Potter"
    ...
  }
}

And my code looks like this:

Map data;
List userData;

Future<List<Result>> _getData(UrlToUse) async {
    var response = await http.get(_baseurl + UrlToUse + 'api_key=' + _key + '&language=' + _lang);
    data = json.decode(response.body);

    userData = data[];  //<--- Doesn´t work. I need this line

    print(userData);
    List<Result> realdata = [];
    realdata.clear();
    for (var e in userData) {
      Result result = Result(
          e['id'],
          e['title'],
          e['overview'],
          e['poster_path'],
          e['backdrop_path'],
          e['release_date'],
          e['datvote_average']);
      realdata.add(result);
    }
    return realdata;
}

If you know a way to change this line, let me know ;D

Upvotes: 4

Views: 21760

Answers (2)

Cristian Bregant
Cristian Bregant

Reputation: 1906

If you want the full procedure you can do this way:

Take your json and copy it in this form: https://app.quicktype.io/

Create your class in flutter and paste your code (that is a json model so you don't have every time to write your json skeleton) on the right column.

Then you will easily refractor your code to:

Future<List<Result>> _getData(UrlToUse) async {
var response = await http.get(_baseurl + UrlToUse + 'api_key=' + _key + '&language=' + _lang);
data = json.decode(response.body);


List<Result> realdata = List<Result>.from(data).map((x) => Result.fromJson(x)));

return realdata;
}

Upvotes: 4

Ravinder Kumar
Ravinder Kumar

Reputation: 8010

Do something like this,

var dataConvertedToJSON = json.decode(onValue);// decode json
ProjectModel model = ProjectModel.fromJson(dataConvertedToJSON);// convert decoded json to model
myList.addAll(model.getData);

Create json to dart model from this online tool

example-

class ProjectModel {
  String title;
  String logo;
  String url;
  List<String> imageArray;

  ProjectModel({this.title, this.logo, this.url, this.imageArray});

  ProjectModel.fromJson(Map<String, dynamic> json) {
    title = json['title'];
    logo = json['logo'];
    url = json['url'];
    imageArray = json['imageArray'].cast<String>();
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['title'] = this.title;
    data['logo'] = this.logo;
    data['url'] = this.url;
    data['imageArray'] = this.imageArray;
    return data;
  }
}

Upvotes: 2

Related Questions