[英]Flutter - Dropdown - Items - Disable?
我在 Flutter 中发现了 DropdownButton 小部件,并使用了这些项目。我现在的问题是,为什么在 dropdownmenuitem 小部件中没有禁用项目的选项? 或者有没有办法做到这一点?
我的想法是我有多个具有相同 itemList 的下拉列表,如果我在下拉列表中选择一个项目,则应该在其他项目中禁用它。 任何的想法?
https://dartpad.dev/d2b1688b14270bdf56ae952adfac93d2
没有官方的方法可以禁用某些DropdownMenuItem
但是您可以通过在选择时不选择禁用的项目并更改其颜色来模拟此功能。 否则,您需要复制DropdownButton
并自己添加此功能。
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: Center(
child: MyStatefulWidget(),
),
),
);
}
}
class MyStatefulWidget extends StatefulWidget {
MyStatefulWidget({Key key}) : super(key: key);
@override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
final disabledItems = ['Free', 'Four'];
String dropdownValue = 'One';
@override
Widget build(BuildContext context) {
return DropdownButton<String>(
value: dropdownValue,
icon: Icon(Icons.arrow_downward),
iconSize: 24,
elevation: 16,
style: TextStyle(color: Colors.deepPurple),
underline: Container(
height: 2,
color: Colors.deepPurpleAccent,
),
onChanged: (String newValue) {
if (!disabledItems.contains(newValue)) {
setState(() {
dropdownValue = newValue;
});
}
},
items: <String>['One', 'Two', 'Free', 'Four']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(
value,
style: TextStyle(
color: disabledItems.contains(value) ? Colors.grey : null,
),
),
);
}).toList(),
);
}
}
一个稍微不同的版本:
创建所有项目,但必须禁用的项目具有 onTap => null && Color = 灰色。
您可以将此解决方案与@humazed 合并,以检查元素是否包含在排除列表中。
String selectedValue;
...
DropdownButtonFormField(
decoration: InputDecoration(
icon: const Icon(Icons.category),
labelText: 'Disabled dropdown menu'),
items: ['a', 'b', 'c'].map((value) {
// normal options
if (value != 'c') {
return DropdownMenuItem<String>(
value: value,
child: new Text(value,
style: new TextStyle(color: Colors.black)),
);
// the disabled one ("c")
} else {
return DropdownMenuItem<String>(
child: Text(value, style: TextStyle(color: Colors.grey)),
onTap: () => null,
);
}
}).toList(),
value: selectedValue,
onChanged: (String newValue) {
setState(() {
selectedValue = newValue;
});
},
),
设置 onTap() => null 并且菜单选项已经被禁用不是很好吗? 就像禁用按钮一样有效。 我已经在 Flutter 的 github 上发送了一个改进请求
试试这个:
return DropdownButtonFormField(
value: dropValue,
items: DropItems.map((String value) {
if (value == "a") {
return DropdownMenuItem<String>(
child: Text(value, style: const TextStyle(color: Colors.grey)),
value: value,
onTap: () => null,
enabled: false, // disable this item
);
}
return DropdownMenuItem<String>(child: Text(value), value: value);
}).toList(),
onTap: (){
// some code
},
onChanged: (){
// some code
},
);
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.