How to make an API request in Flutter
878
The approach is correct but for list you should use list.map for deserializing lists.
Try this, I didn't tested it, I just wrote it looking at your examples
var response = await http.get(
Uri.encodeFull("http://192.168.0.10/api/v1/categories"),
headers: {
"Authorization": "API",
"Accept": "application/json"
}
);
List<Rows> rows = [];
Map map = json.decode(response.body);
List l = map["rows"];
rows = l.map((map) => Rows.fromJson(map)).toList();
Author by
Milan Ciganović
Updated on December 14, 2022Comments
-
Milan Ciganović over 1 year
I'm new to Flutter, so I'm not sure how I am supposed to make an API call, coming from Java where I was using Retrofit.
JSON Response:
{ "total": 13, "rows": [ { "id": 1, "name": "Name" } ] }
Model class:
class Category { int total; List<Rows> rows; Category({this.total, this.rows}); Category.fromJson(Map<String, dynamic> json) { total = json['total']; if (json['rows'] != null) { rows = new List<Rows>(); json['rows'].forEach((v) { rows.add(new Rows.fromJson(v)); }); } } } class Rows { String name; Rows({this.name}); Rows.fromJson(Map<String, dynamic> json) { name = json['name']; } }
Main class
List<Rows> rows = []; Future<List<Rows>> getData() async { var response = await http.get( Uri.encodeFull("http://192.168.0.10/api/v1/categories"), headers: { "Authorization": "API", "Accept": "application/json" } ); var jsonData = json.decode(response.body); }
I'm not sure how to approach I tried getting the object with Rows.fromJson(), but I only get 'Instance of Rows' and by calling name I get null.
-
Milan Ciganović over 4 yearsThanks so much, that worked perfectly. Could you explain to me this line? rows = l.map((map) => Rows.fromJson(map)).toList(); What is exactly => Rows.fromJson(map)).toList();
-
Luca Corradi over 4 yearsIt's because
json.decode(..)
deserialize json to aMap
object and an array in json is deserialized to aList<Map>
. When you accessmap["rows"]
you get a List (implicitly List of Maps). So you need to transform all the maps in the list into object of different type. That is done with thelist.map(..)
function. With the 'map' function every object in the list is used to create a new object withRows.fromJson(..)