Flutter : How put received data on model as nested List
You could use the categoriesFromMap
function to convert the response body into a list of Categories
s. I have included a minimum working example of the get_data
function:
Future<List<Categories>> get_data() async {
var url = 'http://10.0.2.2:8000/api/user/cats_view';
var response = await http.get(url);
var data = categoriesFromMap(response.body);
}
See the documentation here for more information regarding deserializing responses.
Sermed mayi
Updated on December 26, 2022Comments
-
Sermed mayi over 1 year
I am trying to create shopping app by flutter and Laravel for backend ,I created the backend at tested it on postman and worked correctly ,now I want to design the UI by flutter depend on data's come from API ,First of all I want to view all categories and all products of each category ,I receive data from API as this :
[ { "id": 1, "name": "cars", "created_at": "-000001-11-30T00:00:00.000000Z", "updated_at": null, "product": [ { "id": 1, "product_name": "mercides", "category_id": 1, "price": "120000", "sale": "0", "created_at": null, "updated_at": null }, ] }, ]
I made a class in model folder to put data on it :
import 'dart:convert'; List<Categories> categoriesFromMap(String str) => List<Categories>.from(json.decode(str).map((x) => Categories.fromMap(x))); String categoriesToMap(List<Categories> data) => json.encode(List<dynamic>.from(data.map((x) => x.toMap()))); class Categories { Categories({ this.id, this.name, this.product, }); final int id; final String name; final List<Product> product; factory Categories.fromMap(Map<String, dynamic> json) => Categories( id: json["id"], name: json["name"], product: List<Product>.from(json["product"].map((x) => Product.fromMap(x))), ); Map<String, dynamic> toMap() => { "id": id, "name": name, "product": List<dynamic>.from(product.map((x) => x.toMap())), }; } class Product { Product({ this.id, this.productName, this.categoryId, this.price, this.sale, }); final int id; final String productName; final int categoryId; final String price; final String sale; factory Product.fromMap(Map<String, dynamic> json) => Product( id: json["id"], productName: json["product_name"], categoryId: json["category_id"], price: json["price"], sale: json["sale"], ); Map<String, dynamic> toMap() => { "id": id, "product_name": productName, "category_id": categoryId, "price": price, "sale": sale, }; }
Now I want to receive data from URL and convert it as Future List in this function :
Future<List> get_data() async { var url = 'http://10.0.2.2:8000/api/user/cats_view'; var response = await http.get(url); var data = jsonDecode(response.body); }
How can I do it , How can I use categoriesToMap() function on class or any other way?
-
Sermed mayi over 3 yearsThank you I will see the documentation ,it works correctly