Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 614
tobias Avatar asked Oct 15 '25 18:10

tobias


1 Answers

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;
}
like image 134
Cristian Bregant Avatar answered Oct 17 '25 08:10

Cristian Bregant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!