【发布时间】:2021-03-19 22:58:15
【问题描述】:
我正在尝试通过颤振和 Laravel 为后端创建购物应用程序,我在邮递员上测试它创建了后端并且工作正常,现在我想通过颤振设计 UI 取决于来自 API 的数据,首先我想查看所有类别和每个类别的所有产品,我从 API 接收数据是这样的:
[
{
"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
},
]
},
]
我在模型文件夹中创建了一个类来放置数据:
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,
};
}
现在我想从 URL 接收数据并在此函数中将其转换为未来列表:
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);
}
我该怎么做,如何在课堂上使用 categoriesToMap() 函数或任何其他方式?
【问题讨论】: