You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 12:34:56