【发布时间】:2021-04-22 16:47:48
【问题描述】:
我正在使用 Flutter 开发电子商务应用。
我正在为它开发 navDrawer,我可以在类别方面使用一些帮助。
我的类别可以有子类别,子类别也可以有自己的子类别。
基本上,数据集是一个未知维度的数组。
我需要为我的类别和子类别制作一个布尔图,以便我可以跟踪哪些是打开的,以便显示子类别。
这是数据集的一个示例:
{
"id":"41490",
"name":"Electrical Equipment",
"subCategories":[
{
"id":"41492",
"name":"Breakers",
"subCategories":[
{
"id":"167542",
"name":"1 Pole",
"subCategories":[
{
"id":"167577",
"name":"15 Amp",
"subCategories":null
},
{
"id":"167585",
"name":"20 Amp",
"subCategories":null
},
{
"id":"167600",
"name":"30 Amp",
"subCategories":null
},
{
"id":"167606",
"name":"40 Amp",
"subCategories":null
}
]
},
我认为递归是处理此数据集的最佳方式,但我遇到的问题是我无法弄清楚如何在 Dart 中为数组设置动态维度。
我已经想出了如何从数据集中生成我的 listTiles,但我不知道布尔图。
这甚至可能吗,还是我应该研究一种不同的方法?
这是我从数据集中生成 listTiles 的代码:
void setCategories(List categories){
_categories = categories;
int catCount = categories.length;
_categoryList = new ListView.builder(
//shrinkWrap: true,
//physics: ClampingScrollPhysics(),
padding:EdgeInsets.all(0.0),
itemCount: catCount,
itemBuilder: (BuildContext context, int index) => buildCategories(context, index),
);
}
Widget buildCategories(BuildContext context, int index){
if(_categories[index]['subCategories']!=null){
//TODO: call buildSubCategories with depth of 1 parameter
return Container(
height: 30.0,
child: ListTile(
title: Row(
children:[
Text(" "+_categories[index]['name']),
Transform.scale(
scale: 0.75,
child:
Icon(Icons.arrow_back)
)
]
),
onTap: () {
//TODO: implement boolean map here
}
),
padding: EdgeInsets.all(0.0),
margin: EdgeInsets.all(0.0)
);
} else {
return Container(
height: 30.0,
child: ListTile(
title: Text(" "+_categories[index]['name']),
onTap: () {
}
),
padding: EdgeInsets.all(0.0),
margin: EdgeInsets.all(0.0)
);
}
}
Widget buildSubCategories(var parent, int depth){
List subCategoryList = parent['subCategories'];
int subCategoryCount = subCategoryList.length;
if(parent['subCategories']!=null){
//for each subCategory
//if subCategory has subCategories
//recurse subCategory with depth
buildSubCategories(parent['subCategories'], depth++);
//TODO: implement boolean map here
} else {
//
}
}
void generateCategoryBooleanMap(){
//TODO: generate boolean map here
//TODO: boolean map needs to have a undetermined amount of depth levels
}
感谢任何见解,即使这意味着我必须使用不同的范例。
【问题讨论】:
-
id在您的数据中是唯一的吗?因为如果是这种情况,您也可以制作一个简单的Set<String>。然后你可以这样做,如果id在Set中,则表示true,如果id缺失,则表示错误。 -
所有 ID 都是唯一的,每个项目都有一个 ID。我不太清楚你的意思?
-
添加了一个解决方案,其中包含我的意思的示例。