Что вы можете сделать, так это создать класс CountryOption
с key
(«США» в вашем примере) и 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'),
];
}
Сообщите мне, если что-то неясно или у вас есть вопросы.