Flutter基于List<Map<String, Object>>实现汽车品牌车型联动二级下拉框
Flutter二级联动下拉选择实现方案
第一步:补充状态变量
在当前页面的State类中新增存储选中车型的变量,修改后你的状态变量部分如下:
// 原有存储选中品牌的变量 String? _mySelection; // 新增存储选中车型的变量 String? _selectedModel;
第二步:修改第一个品牌下拉框的联动逻辑
在品牌选中的回调中,同步清空上一次选中的车型,避免数据错乱:
onChanged: (newValue) { setState(() { _mySelection = newValue!; // 切换品牌时重置车型选择 _selectedModel = null; }); print(_mySelection); },
第三步:重写第二个车型下拉框的完整逻辑
把原有的车型下拉框代码替换为以下内容:
Padding( padding: const EdgeInsets.only(left: 24, top: 24, bottom: 10), child: Text( "Select your car model:", style: Theme.of(context) .textTheme .subtitle1! .copyWith(color: Theme.of(context).hintColor), ), ), Padding( padding: EdgeInsets.symmetric(horizontal: 24.0), child: DropdownButton<String>( isDense: true, hint: new Text("Select"), value: _selectedModel, onChanged: (newValue) { setState(() { _selectedModel = newValue!; }); print(_selectedModel); }, // 根据选中的品牌动态生成车型选项 items: _mySelection == null ? [] : (MapUtils.cars .firstWhere((car) => car["brand"] == _mySelection)["models"] as List) .map<DropdownMenuItem<String>>((model) { return DropdownMenuItem<String>( value: model.toString(), child: Text(model), ); }).toList(), ), ),
可选优化
如果要在未选择品牌时给用户提示,可以把空列表换成带提示的不可选选项,或者直接禁用第二个下拉框。
内容的提问来源于stack exchange,提问作者Jayson Tamayo
相关产品推荐
相关产品推荐

