首页 > 解决方案 > 从嵌套列表中检索信息 (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();
    });

我知道我的代码可能没有任何意义,你可以给我任何建议来完全改变数据结构。现在(暂时不使用数据库),我想根据所选商店显示可用的产品。

我希望每个人都有一个安全和富有成效的一天。谢谢!

标签: listflutter

解决方案


我不禁注意到 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)]

这是我们期望找到的。


推荐阅读