Flutter中如何根据DropdownMenuItem选中值展示REST API对应数据
你已写好的getData接口请求方法不需要调整,可以直接复用,完整实现流程如下:
1. 确认实体类结构
首先保证你的ObjectName实体类包含id、name、description三个字段,参考定义:
class ObjectName { final String id; final String name; final String description; ObjectName({ required this.id, required this.name, required this.description, }); factory ObjectName.fromJson(Map<String, dynamic> json) { return ObjectName( id: json['id'], name: json['name'], description: json['description'], ); } }
2. 定义页面状态变量
在对应页面的State类中定义两个状态变量,分别存储异步请求任务和选中的条目:
Future<List<ObjectName>>? _futureData; ObjectName? _selectedItem;
3. 初始化接口请求
在initState生命周期中触发接口请求:
@override void initState() { super.initState(); _futureData = getData(); }
4. 构建UI界面
使用FutureBuilder处理异步加载的不同状态,同时渲染下拉选择组件和选中结果:
@override Widget build(BuildContext context) { return Scaffold( body: Padding( padding: EdgeInsets.all(16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // 下拉选择组件 FutureBuilder<List<ObjectName>>( future: _futureData, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return CircularProgressIndicator(); } if (snapshot.hasError) { return Text("加载失败:${snapshot.error}"); } final itemList = snapshot.data!; return DropdownButton<ObjectName>( hint: Text("请选择选项"), value: _selectedItem, items: itemList.map((item) { return DropdownMenuItem( value: item, child: Text(item.name), ); }).toList(), onChanged: (value) { setState(() { _selectedItem = value; }); }, ); }, ), SizedBox(height: 20), // 展示选中结果 if (_selectedItem != null) Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text("名称:${_selectedItem!.name}"), Text("描述:${_selectedItem!.description}"), ], ) ], ), ), ); }
如果你需要单独用id作为选中值的存储介质,也可以将列表转成id为key的映射表,选中后通过id查询对应条目即可:
// 定义选中的id String? _selectedId; // 列表转映射表 Map<String, ObjectName> itemMap = { for (var item in itemList) item.id: item }; // 选中后取值 ObjectName? selectedItem = itemMap[_selectedId];
内容的提问来源于stack exchange,提问作者xen
相关产品推荐
相关产品推荐

