Flutter问题:如何将国家下拉选框的前缀列表传递至前缀下拉选框
问题解决方案
核心问题是你把状态变量定义在了build方法内部,每次调用setState触发页面重建时,build方法会重新执行,这些局部变量会被重新初始化,导致第二个下拉框始终拿到空列表。
解决步骤:
- 将
_selectedCountryIso、_selectedPrefix、selectedCountryPrefixes移到_CountriesViewState类的成员变量位置,作为State的状态属性。 - 保留
countriesState和countryNames在build方法内,因为它们是从Provider监听获取的实时数据。
修改后的代码示例:
class _CountriesViewState extends ConsumerState { // 把状态变量移到类成员位置 String? _selectedCountryIso; String? _selectedPrefix; List<String> selectedCountryPrefixes = []; @override Widget build(BuildContext context) { final countriesState = ref.watch(countriesProvider); final List<String> countryNames = countriesState.countries.map((country) => country.countryName).toList(); return Padding( padding: const EdgeInsets.symmetric(horizontal: 18.0), child: Form( child: Column( children: [ CustomDropdown( labelText: 'País', items: countryNames, value: _selectedCountryIso, onSelectionChanged: (newValue) { setState(() { // 直接给类成员变量赋值 selectedCountryPrefixes = countriesState.countries .firstWhere((country) => country.countryName == newValue) .prefix .map((prefix) => prefix['Prefix']!) .toList(); }); print(selectedCountryPrefixes); }, onChanged: (newValue) {}, ), CustomDropdown( labelText: 'Prefijo', items: selectedCountryPrefixes, value: _selectedPrefix, onSelectionChanged: (newValue) {}, onChanged: (newValue) {}, ), ], ), ), ); } }
这样修改后,selectedCountryPrefixes作为State的成员变量,会在页面重建时保留之前赋值的内容,第二个下拉框就能正确加载对应的前缀列表了。
内容的提问来源于stack exchange,提问作者jhon1946
相关产品推荐
相关产品推荐

