例如,如果用户在幕后选择“美利坚合众国”,那么我只想获得一个“美国”值。我该如何实现?
这是我的按钮:DropdownButton<String>(
isExpanded: true,
underline: SizedBox(),
icon: SvgPicture.asset("assets/icons/dropdown.svg"),
value: dropdownValue,
items: [
'Nepal',
'India',
'United States',
'Denmark',
'UK',
'World Wide'
].map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (newValue) {
setState(() {
dropdownValue = newValue;
});
},
),
[您可以做的是创建一个带有CountryOption
(在您的示例中为'USA')和key
(在您的示例中为'United States')的fullName
类。
然后您创建CountryOption
而不是String
的下拉列表,因此您可以存储当前选择的CountryOption
,并且key
和fullName
属性都可供以后使用。
[我也建议您仅一次加载项目列表,而不是在每次重建时加载。
import 'package:flutter/material.dart';
class CountriesButton extends StatefulWidget {
const CountriesButton({Key key}) : super(key: key);
@override
_CountriesButtonState createState() => _CountriesButtonState();
}
class _CountriesButtonState extends State<CountriesButton> {
List<DropdownMenuItem<CountryOption>> _countryItems;
CountryOption selectedCountry;
@override
void initState() {
// Get all countries
List<CountryOption> countries = CountryOption.allCountries;
// Initialise your items only once
_countryItems = countries.map<DropdownMenuItem<CountryOption>>(
(CountryOption countryOption) {
return DropdownMenuItem<CountryOption>(
value: countryOption,
child: Text(countryOption.fullName),
);
},
).toList();
// Initialiste your dropdown with the first country in the list
// (might be different in your specific scenario)
selectedCountry = countries[0];
super.initState();
}
@override
Widget build(BuildContext context) {
return Container(
child: DropdownButton<CountryOption>(
isExpanded: true,
underline: SizedBox(),
icon: SvgPicture.asset("assets/icons/dropdown.svg"),
value: selectedCountry,
items: _countryItems,
onChanged: (newValue) {
setState(() {
selectedCountry = newValue;
});
},
),
);
}
}
class CountryOption {
final String key;
final String fullName;
CountryOption(this.key, this.fullName);
static List<CountryOption> get allCountries => [
CountryOption('nepal', 'Nepal'),
CountryOption('india', 'India'),
CountryOption('usa', 'United States'),
CountryOption('denmark', 'Denmark'),
CountryOption('uk', 'UK'),
CountryOption('world', 'World Wide'),
];
}
让我知道是否不清楚或有任何疑问。