Flutter二级下拉按钮实现:国家城市选择绑定ID方案咨询
Flutter 两级联动下拉选择(带ID绑定)实现方案
实现思路
- 补全你提供的实体类结构,国家实体命名为
Country,补充构造方法方便初始化测试数据 - 替换原有字符串类型的国家/城市存储结构,改用实体类存储,天然保留ID、名称、子级关联关系
- 调整
DropdownButton的泛型为对应实体类,选中后可直接读取选中项的ID属性用于后续业务逻辑 - 新增第二级城市下拉组件,跟随国家选中状态联动更新可选列表
完整可运行代码
import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: '两级下拉Demo', home: Scaffold( appBar: AppBar(title: const Text('两级联动下拉选择')), body: const MultiLevelDropdown(), ), ); } } // 补全的实体类定义 class Country { int id; String name; List<City> cities; Country({required this.id, required this.name, required this.cities}); } class City { int id; String name; City({required this.id, required this.name}); } class MultiLevelDropdown extends StatefulWidget { const MultiLevelDropdown({super.key}); @override State<MultiLevelDropdown> createState() => _MultiLevelDropdownState(); } class _MultiLevelDropdownState extends State<MultiLevelDropdown> { // 初始化测试数据,包含ID和关联的城市列表 final List<Country> countries = [ Country( id: 1, name: 'USA', cities: [ City(id: 101, name: 'Texas'), City(id: 102, name: 'Florida'), City(id: 103, name: 'California'), ], ), Country( id: 2, name: 'India', cities: [ City(id: 201, name: 'New Delhi'), City(id: 202, name: 'Bihar'), City(id: 203, name: 'Rajasthan'), ], ) ]; Country? selectedCountry; City? selectedCity; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(20), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ // 国家选择下拉 DropdownButton<Country>( isExpanded: true, hint: const Text('选择国家'), value: selectedCountry, items: countries.map((Country country) { return DropdownMenuItem<Country>( value: country, child: Text(country.name), ); }).toList(), onChanged: (value) { setState(() { selectedCountry = value; selectedCity = null; // 切换国家时清空已选城市 }); }, ), const SizedBox(height: 20), // 城市选择下拉,未选国家时禁用 DropdownButton<City>( isExpanded: true, hint: const Text('选择城市'), value: selectedCity, items: selectedCountry?.cities.map((City city) { return DropdownMenuItem<City>( value: city, child: Text(city.name), ); }).toList() ?? [], onChanged: (value) { setState(() { selectedCity = value; }); // 选中城市后可直接取ID使用:selectedCity?.id debugPrint('选中城市ID:${selectedCity?.id},城市名:${selectedCity?.name}'); }, ), const SizedBox(height: 30), // 展示选中结果 Text( '选中结果:\n国家ID:${selectedCountry?.id ?? '未选择'} 国家名:${selectedCountry?.name ?? '未选择'}\n城市ID:${selectedCity?.id ?? '未选择'} 城市名:${selectedCity?.name ?? '未选择'}', style: const TextStyle(fontSize: 16), ) ], ), ); } }
使用说明
选中国家或城市后,直接读取selectedCountry.id即可拿到国家ID,selectedCity.id即可拿到城市ID,可直接用于后续接口请求、数据存储等业务逻辑。
内容的提问来源于stack exchange,提问作者Ильяс Бадыганов
相关产品推荐
相关产品推荐

