0

[在此处输入图像描述][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
4

1 回答 1

0

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

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;
}
于 2021-12-25T21:51:17.493 回答