我正在使用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
}
任何见解都值得赞赏,即使这意味着我必须使用不同的范式。
使用Set
跟踪哪个id
打开的示例:
void main() {
final idHandler = IdHandler();
print(idHandler.isIdOpen('MyId')); // false
idHandler.openId('MyId');
print(idHandler.isIdOpen('MyId')); // true
idHandler.closeId('MyId');
print(idHandler.isIdOpen('MyId')); // false
idHandler.openId('MyId');
print(idHandler.isIdOpen('MyId')); // true
idHandler.closeAll();
print(idHandler.isIdOpen('MyId')); // false
}
class IdHandler {
final Set<String> _openIds = {};
void openId(String id) => _openIds.add(id);
void closeId(String id) => _openIds.remove(id);
void closeAll() => _openIds.clear();
bool isIdOpen(String id) => _openIds.contains(id);
}