[英]multiple selection inside the drop down menu in flutter
您可以通过使用自定义小部件作为 DropdownMenuItem 的子级来实现这一点,其中自定义小部件需要是有状态的,以便它可以处理自己的 state 以显示复选标记或其他内容。 它应该有它自己的 onTap 方法,所以 DropdownMenuItem onTap 不会触发和 select 选项,关闭下拉菜单。 您还需要有一个选项来完成选择。
但是我建议您为这种情况寻找另一种方法以获得更好的可用性,例如一个对话框,您可以在其中 select 多个选项:flutter 中是否有与 Z4C4AD5FCA2E7A3F74DBB1CED00381AAA 中的“选择多个”元素等效的小部件
代码:-
class CustomMultiselectDropDown extends StatefulWidget {
final Function(List<String>) selectedList;
final List<String> listOFStrings;
CustomMultiselectDropDown(
{required this.selectedList, required this.listOFStrings});
@override
createState() {
return new _CustomMultiselectDropDownState();
}
}
class _CustomMultiselectDropDownState extends State<CustomMultiselectDropDown> {
List<String> listOFSelectedItem = [];
String selectedText = "";
@override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
return Container(
margin: EdgeInsets.only(top: 10.0),
decoration:
BoxDecoration(border: Border.all(color: PrimeDentalColors.grey1)),
child: ExpansionTile(
iconColor: PrimeDentalColors.grey,
title: Text(
listOFSelectedItem.isEmpty ? "Select" : listOFSelectedItem[0],
style: GoogleFonts.poppins(
textStyle: TextStyle(
color: PrimeDentalColors.grey,
fontWeight: FontWeight.w400,
fontSize: 15.0,
),
),
),
children: <Widget>[
new ListView.builder(
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: widget.listOFStrings.length,
itemBuilder: (BuildContext context, int index) {
return Container(
margin: EdgeInsets.only(bottom: 8.0),
child: _ViewItem(
item: widget.listOFStrings[index],
selected: (val) {
selectedText = val;
if (listOFSelectedItem.contains(val)) {
listOFSelectedItem.remove(val);
} else {
listOFSelectedItem.add(val);
}
widget.selectedList(listOFSelectedItem);
setState(() {});
},
itemSelected: listOFSelectedItem
.contains(widget.listOFStrings[index])),
);
},
),
],
),
);
}
}
class _ViewItem extends StatelessWidget {
String item;
bool itemSelected;
final Function(String) selected;
_ViewItem(
{required this.item, required this.itemSelected, required this.selected});
@override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
return Padding(
padding:
EdgeInsets.only(left: size.width * .032, right: size.width * .098),
child: Row(
children: [
SizedBox(
height: 24.0,
width: 24.0,
child: Checkbox(
value: itemSelected,
onChanged: (val) {
selected(item);
},
activeColor: PrimeDentalColors.blue,
),
),
SizedBox(
width: size.width * .025,
),
Text(
item,
style: GoogleFonts.poppins(
textStyle: TextStyle(
color: PrimeDentalColors.grey,
fontWeight: FontWeight.w400,
fontSize: 17.0,
),
),
),
],
),
);
}
}
您可以使用以下 package
https://pub.dev/packages/multiselect
它有一个基于下拉的实现而不是对话框来显示选项。
PS:我在最近的一个项目中需要这个功能,并且必须创建自己的小部件。 这是我的实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.