在Flutter中,我试图用以下json创建一个依赖下拉列表。
我希望下拉菜单是这种格式
第一,独立下拉
数据名称
第二,依赖下拉
数据集的子级索引
第三,依赖下拉
选择上述下拉列表的子项(…你好1,你好2…(
[
{
"dataName": "data1",
"dataSets": [
["hello 1", "hello 2", "hello 3"],
["hi 1", "hi 2", "hi 3", "hi 4"]
]
},
{
"dataName": "data2",
"dataSets": [
["2nd 1", "2nd 2", "2nd 3"],
["let 1", "let 2", "let 3", "let 4"]
]
}
]
这里是第一步:将json解析为一个类模型,然后创建一个模型列表。第二步构建DropdownMenuItem列表以供DropDown按钮使用。在第一个下拉按钮(级别1(选择中创建_currentResultClass变量。步骤3:在级别1的dataName上进行筛选并找到模型,然后根据该dataName的筛选器填充下拉菜单项。
class ResultClass
{
String?dataName;
//List<List<String>> dataSets= new List.generate(n, (i) => []);
List<List<String>>? dataSets= [];
ResultClass({this.dataName,this.dataSets});
ResultClass.fromJson(Map<String, dynamic> json) {
dataName = json['dataName'];
dataSets = json['dataSets'];
}
Map<String,dynamic> toJson(){
final Map<String,dynamic>data = new Map<String,dynamic>();
data['dataName']=this.dataName;
data['dataSet']=this.dataSets;
return data;
}
}
class TestDropDown extends StatefulWidget {
TestDropDown({Key? key}) : super(key: key);
@override
State<TestDropDown> createState() => _TestDropDownState();
}
class _TestDropDownState extends State<TestDropDown> {
ResultClass ? _currentResultClassLevel1;
String ? _currentStringLevel2;
List<ResultClass> lst=[];
List<DropdownMenuItem<ResultClass>>? itemsLevel1;
var data=[
{
"dataName": "data1",
"dataSets": [
["hello 1", "hello 2", "hello 3"],
["hi 1", "hi 2", "hi 3", "hi 4"]
]
},
{
"dataName": "data2",
"dataSets": [
["2nd 1", "2nd 2", "2nd 3"],
["let 1", "let 2", "let 3", "let 4"]
]
}
];
@override
void initState() {
// TODO: implement initState
super.initState();
for(var i=0; i<data.length; i++)
{
ResultClass model = ResultClass.fromJson(data[i]);
lst.add(model);
if (i==0)
{
_currentResultClassLevel1=model;
}
}
itemsLevel1 = lst
.map((item) => DropdownMenuItem<ResultClass>(
child: Text(item.dataName??""), value: item))
.toList();
}
@override
Widget build(BuildContext context) {
List<ResultClass> models = lst.where((item)=> item.dataName==_currentResultClassLevel1?.dataName).toList();
List<String> strings=[];
models.forEach((model)=>
model.dataSets?[0].forEach((element)=>strings.add(element)));
var itemsLevel2= strings.map((item) => DropdownMenuItem<String>(
child: Text(item), value: item))
.toList();
return Scaffold(appBar: AppBar(title: Text("Dropdown"),),body:
Column(children: [
DropdownButton<ResultClass>(items: itemsLevel1,
value: this._currentResultClassLevel1,
onChanged: (item){
setState(() {
_currentResultClassLevel1=item;
});
},),
DropdownButton<String>(items: itemsLevel2,
value: this._currentStringLevel2,
onChanged: (item){
setState((){
_currentStringLevel2=item;
});
},),
SizedBox(height:50)
],)
);
}
}