flutter - Flutter:自定义下拉按钮功能不显示所选值
问题描述
我正在尝试制作一个返回下拉菜单的自定义函数。该函数接受 3 个参数:menuTitle、selectedValue 和字符串列表。
List<String> cities= ['Rome', 'London', 'Paris'];
String selectedCity;
String title='Select a city';
Widget _buildDropdown(
String menuTitle, String selectedItem, List<String> list) {
return Container(
width: MediaQuery.of(context).size.width * 0.8,
margin: EdgeInsets.all(10.0),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey[300]),
borderRadius: BorderRadius.circular(10.0)),
child: DropdownButtonHideUnderline(
child: ButtonTheme(
alignedDropdown: true,
child: DropdownButton<String>(
isExpanded: true,
hint: Text(
menuTitle.toUpperCase(),
style: GoogleFonts.lato(
textStyle: TextStyle(
color: Colors.grey[500],
fontWeight: FontWeight.bold,
)),
),
value: selectedItem,
items: list.map((String val) {
return DropdownMenuItem(
value: val,
child: Text(
val.toUpperCase(),
style: GoogleFonts.lato(
textStyle: TextStyle(
color: Colors.grey[500],
)),
),
);
}).toList(),
onChanged: (String value) {
setState(() {
selectedItem = value;
});
},
),
),
),
);
}
下拉菜单显示所有可用选项,但选择一个后,我只能看到提示文本而不是所选值。我将不胜感激任何帮助。
解决方案
为了让您的下拉列表反映您的 selectedValue,它应该是状态的一部分。所以按照下面的代码所示。我已经测试了这段代码及其对我的工作。
class _MyAppState extends State<MyApp> {
List<String> cities= ['Rome', 'London', 'Paris'];
//Initialize your selectedItem to selectedCity
//default selectedCity
String selectedCity='Rome';
String title='Select a city';
@override
Widget build(BuildContext context) {
Color color=Colors.blueAccent;
int x=color.value;
return MaterialApp(
home: Scaffold(
body: Column(
children: <Widget>[_buildDropdown("Title","",cities)],
),
),
);
}
Widget _buildDropdown(
String menuTitle, String selectedItem, List<String> list) {
return Container(
margin: EdgeInsets.all(10.0),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey[300]),
borderRadius: BorderRadius.circular(10.0)),
child: DropdownButtonHideUnderline(
child: ButtonTheme(
alignedDropdown: true,
child: DropdownButton<String>(
isExpanded: true,
hint: Text(
menuTitle.toUpperCase(),
),
value: selectedCity,
items: list.map((String val) {
return DropdownMenuItem(
value: val,
child: Text(
val.toUpperCase(),
),
);
}).toList(),
onChanged: (String value) {
setState(() {
selectedCity = value;
});
},
),
),
),
);
}
}
推荐阅读
- mysql - 根据列选择对应的列
- python-3.x - Pythonnet 没有名为 System 的模块
- android - 如何从 Android 设备向 BLE 设备发送无符号整数?
- javascript - 带有响应式行号的普通预格式化文本样式
- c# - LeftArrow 预设形状公式中缺少“dy”属性
- .net - linux systemd:路径不是绝对的
- flutter - 全屏细节覆盖与投影仪位置
- python - Matplotlib animate 似乎没有运行功能?
- shopify - Shopify 显示小部件添加块选项取决于订阅或取消订阅
- swift - 如何在swift中从布尔值中隐藏tableview行