我正在尝试使用DropdownButton
构建多个ListView.builder
,就像用户单击 float 操作按钮一样多
new FloatingActionButton(
onPressed: () {
setState(() {
counter++;
});
},
child: new Icon(Icons.add),
)
new ListView.builder(
itemBuilder: (BuildContext context, int index) {
return buildfields(index); },
itemCount: counter,
scrollDirection: Axis.vertical,
)
new DropdownButton<String>(
onChanged: (String value) { setState((){
setUn();
_unit = value;
});
},
hint: new Text('Course Unit'),
value: _unit,
items: <String>["1", "2", "3", "4", "5"].map((String value) {
return new DropdownMenuItem<String>(
value: value,
child: new Text(value),
);
}).toList(),
)
问题是,当用户生成多个
DropdownButton
并为“一个”选择值时,其他所有DropdownButton
都将其“值”更改为新选择的值。如何为每个生成的DropdownButton
设置唯一的ID? 最佳答案
使用ListView.Builder和一个列表来尝试保存值。
class MultipleDropDownPage extends StatefulWidget {
MultipleDropDownPage({Key key}) : super(key: key);
@override
_MultipleDropDownPageState createState() => new _MultipleDropDownPageState();
}
class _MultipleDropDownPageState extends State<MultipleDropDownPage> {
List<String> selectedValues;
@override
void initState() {
// TODO: implement initState
super.initState();
selectedValues = [];
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: Text('Multi Drop'),
),
body: new ListView.builder(
itemCount: selectedValues.length,
itemBuilder: (context, index) {
return new DropdownButton<String>(
onChanged: (String value) {
setState(() {
selectedValues[index] = value;
});
},
hint: new Text('Course Unit'),
value: selectedValues[index],
items: <String>["1", "2", "3", "4", "5"].map((String value) {
return new DropdownMenuItem<String>(
value: value,
child: new Text(value),
);
}).toList(),
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
selectedValues.add(null);
});
},
),
);
}
}
关于dart - 在Flutter中获取选定的DropdownMenuItem的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52116722/