【问题标题】:Get data from list inside another list in flutter在颤动中从另一个列表中的列表中获取数据
【发布时间】:2022-01-25 13:17:11
【问题描述】:

[在此处输入图片描述][1] 我正在用虚拟模型创建一个维护应用程序。

我想要实现的是,当用户选择主类别时,屏幕应导航到子类别,然后当用户选择子类别时,屏幕应导航到超子类别。我已经将主要类别数据带到了 GridView.builder

现在我想获取子类别 iconPath 和名称来创建一个新的 GridView.builder

final List<Category> mianCategory = [
  Category(
    iconPath: 'assets/svg/electrical.svg',
    name: 'Electrical',
    subCategory: [
      Category(
        iconPath: 'assets/svg/plug.svg',
        name: 'Plug',
        superSubCategory: [
          'Plug Not Working',
          'Fuse Neeeds Replacement',
          'Other'
        ],
      ),
  
      Category(
        iconPath: 'assets/svg/communication.svg',
        name: 'Communication',
        superSubCategory: [
          'Plug Not Working',
          'Fuse Neeeds Replacement',
          'Other'
        ],
      ),
    ],
  ),

这是我的模型

class Category {
  final String? iconPath;
  final String name;
  final List<Category>? subCategory;
  final List<String>? superSubCategory;

  const Category({
    this.iconPath,
    required this.name,
    this.subCategory,
    this.superSubCategory,
  });
}


  [1]: https://i.stack.imgur.com/UL79U.png

【问题讨论】:

  • 如果需要可以使用嵌套列表

标签: flutter dart flutter-listview flutter-gridview


【解决方案1】:

如果我正确理解了您的问题,您可以通过递归来做到这一点:

List<String> getIconPaths(List<Category> categories) {
  List<String> iconPaths = [];
  categories.forEach((e) {
    if (e.subCategory?.isNotEmpty ?? false) {
      iconPaths.addAll(getIconPaths(e.children!));
    }
    if (e.iconPath != null) iconPaths.add(e.iconPath);
  });
  return iconPaths;
}

List<String> getsuperSubCategories(List<Category> categories) {
  List<String> superSubCategories = [];
  categories.forEach((e) {
    if (e.subCategory?.isNotEmpty ?? false) {
      superSubCategories.addAll(getsuperSubCategories(e.children!));
    }
    if (e.superSubCategory != null) superSubCategories.addAll(e.superSubCategory);
  });
  return superSubCategories;
}

【讨论】:

  • 谢谢。我编辑了问题以使其更清楚,还附上了一张照片i.stack.imgur.com/UL79U.png
  • 我用flutter Riverpod解决了这个问题谢谢
猜你喜欢
  • 2021-04-09
  • 2022-01-17
  • 1970-01-01
  • 2011-09-13
  • 1970-01-01
  • 2020-11-17
  • 1970-01-01
  • 1970-01-01
  • 2018-12-08
相关资源
最近更新 更多