list - 从嵌套列表中检索信息 (Flutter)
问题描述
对于其他人来说,我似乎很可能是一个简单的问题,但由于某种原因,我似乎无法解决。我是一个完整的 Flutter 菜鸟,但有编码经验。我希望获得有关结构化数据的提示,并且我创建了一个包含另一个列表的列表,如下所示:
class Store{
final String name;
final String image;
final List <Product> products; // this is defined in another class, and it requires a name(string), description(string), price (double)
Store({required this.name, required this.image, required this.features, required this.price})
List <Store> store= [
Store(name: "Ikea:, image: "ikealogo.png",
products :[Product(name: "wood table", description: "a very nice wood table", price: 12.50),
Product(name: "comfy chair", description: "a very nice leather chair", price: 10.50),
Product(name: "awesome lamp", description: "an ultra bright lamp", price: 5.50),]),
Store(name: "Bestbuy:, image: "bestbuylogo.png",
products :[Product(name: "television", description: "a very nice television", price: 350.00),
Product(name: "radio", description: "a very loud radio", price: 15.50),
Product(name: "cellphone", description: "a very small phone", price: 78.50),]),
];
}
基本上,我还有 20 多个这样的东西,遵循相同的格式。
现在对于我的问题,我似乎无法从嵌套在“商店”中的“产品”信息中创建一个列表。我可以很好地使用 Store 创建列表,并且可以调用 UI 的所有部分的名称和徽标。我的挑战是在选择商店后获取产品信息,因为当我将鼠标悬停在它上面时,我当前使用的代码显示“Iterable”。另一方面,当我在另一条路线上定义或调用商店列表时,我得到“列表”就好了。
@override
Widget build(BuildContext context) {
final product = Store.store.map((store) {
final productlist = store.products.toList();
});
我知道我的代码可能没有任何意义,你可以给我任何建议来完全改变数据结构。现在(暂时不使用数据库),我想根据所选商店显示可用的产品。
我希望每个人都有一个安全和富有成效的一天。谢谢!
解决方案
我不禁注意到 Store 类中的 store 不是静态变量,这意味着 Store.store 不应该是可访问的。但是,如果 store 是 Store 类 Store.store 中的静态变量,则将起作用。所以,
class Product {
String name;
Product(this.name);
@override
String toString() {
return "Product($name)";
}
}
class Store {
List<Product> products;
Store(this.products);
static List<Store> stores = [
Store([
Product("Soap"),
Product("Bar"),
]),
Store([
Product("Sponge"),
Product("ChocoBar"),
]),
];
}
void main() {
print(Store.stores[0].products);
print(Store.stores[1].products);
}
将产生以下输出:
[Product(Soap), Product(Bar)]
[Product(Sponge), Product(ChocoBar)]
这是我们期望找到的。
推荐阅读
- ruby-on-rails - Selecting a nested record to share show page of with selected users in action mailer via checkbox selection
- postgresql - 不在 Postgresql 中使用“开始事务”和“提交”语句
- android - Android Studio 活动 Java 文件无法识别 XML
- javascript - How to execute a script by call his id
- r - group_by(Country.Region) 中的错误:找不到对象“Country.Region”
- python - 使用应用程序身份验证时出现 KustoServiceError
- r - 左调整 (hjust = 0) 垂直 x 轴标签在具有自由比例的刻面上
- rest - HttpGetAttribute 在核心 Web api 中不起作用
- java - 如何在 Android Studio 的自定义 Arraylist 中对日期进行排序?
- reactjs - How do make a loading progress when I fetching an API in login function?