英文:
How to Create a Single Selected Dropdown List in Flutter?
问题
我是一个Flutter初学者。如何在Flutter中创建一个单选的下拉列表?像这样。我尝试过,但没有得到我想要的结果。
String dropdownvalue = 'Bahrain';
Container(
width: 308,
child: DropdownButton(
// 初始值
value: dropdownvalue,
// 下箭头图标
icon: const Icon(Icons.keyboard_arrow_down),
// 项目列表数组
items: ['Bahrain', 'Option 2', 'Option 3', 'Option 4']
.map((String item) {
return DropdownMenuItem(
value: item,
child: Text(item),
);
}).toList(),
// 选择所需选项后,它会将按钮的值更改为所选值
onChanged: (String? newValue) {
setState(() {
dropdownvalue = newValue!;
});
},
),
);
英文:
I am a flutter beginner. How to Create a Single Selected Dropdown List in Flutter?
Like This.<br>
I tried, but I didn't get what I wanted.
String dropdownvalue = 'Bahrain';
Container(
width: 308,
child: DropdownButton(
// Initial Value
value: dropdownvalue,
// Down Arrow Icon
icon: const Icon(Icons.keyboard_arrow_down),
// Array list of items
items: dropdownvalue.map((String dropdownvalue) {
return DropdownMenuItem(
value: dropdownvalue,
child: Text(dropdownvalue),
);
}).toList(),
// After selecting the desired option,it will
// change button value to selected value
onChanged: (String? newValue) {
setState(() {
dropdownvalue = newValue!;
});
},
),
),
答案1
得分: 1
以下是代码部分的中文翻译:
class _YourState extends State<MyHomePage> {
List<String> countries = [
'巴林',
'印度',
'伊拉克',
'美国',
];
String? dropdownvalue;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: DropdownButton(
// 初始值
value: dropdownvalue,
icon: const Icon(Icons.keyboard_arrow_down),
isExpanded: true,
items: countries.map((String dropdownvalue) {
return DropdownMenuItem(
value: dropdownvalue,
child: Text(dropdownvalue),
);
}).toList(),
hint: Text('国家'),
onChanged: (String? newValue) {
setState(() {
dropdownvalue = newValue!;
});
},
),
),
);
}
}
英文:
You should have list of items and selectedItem to manage the list and selection state.
class _YourState extends State<MyHomePage> {
List<String> countries = [
'Bahrain',
'India',
'Iraq',
'America',
];
String? dropdownvalue ;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: DropdownButton(
// Initial Value
value: dropdownvalue,
icon: const Icon(Icons.keyboard_arrow_down),
isExpanded: true,
items: countries.map((String dropdownvalue) {
return DropdownMenuItem(
value: dropdownvalue,
child: Text(dropdownvalue),
);
}).toList(),
hint: Text('Country'),
onChanged: (String? newValue) {
setState(() {
dropdownvalue = newValue!;
});
},
),
),
);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论