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

如何将Flutter中API返回的Offices列表转为Dropdown选项?

实现Flutter Dropdown组件展示Offices列表

你已经成功通过API获取到Offices列表,接下来可以按照以下步骤实现Dropdown组件,将name作为显示文本,value作为选项值:

1. 修正状态变量与数据获取逻辑

首先,你的getCust()方法中,offices被直接赋值为Future对象,无法直接用于生成Dropdown选项。需要先等待异步请求完成,再更新状态:

假设你的State类中定义了以下状态变量:

Map<String, dynamic>? data;
List<Offices>? offices;
Offices? selectedOffice; // 存储选中的Office项

修改getCust()方法:

Future<Map<String, dynamic>?> getCust() async {
  Uri url = Uri.parse("http://deltaprima.rmdoo.com/api/business");
  var response = await http.get(url);

  if (response.statusCode != 200) {
    print("error");
    return null;
  } else {
    final fetchedData = jsonDecode(response.body) as Map<String, dynamic>;
    // 等待getOffices请求完成,获取实际列表数据
    final fetchedOffices = await DeltaPrima.getOffices(fetchedData["CODD_VALU"]);
    setState(() {
      data = fetchedData;
      offices = fetchedOffices;
      // 可选:默认选中第一个选项
      selectedOffice = offices?.first;
    });
    return fetchedData;
  }
}

2. 实现DropdownButton组件

在build()方法中添加Dropdown组件,利用offices列表生成选项:

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: Center(
      child: offices == null 
          ? const CircularProgressIndicator() // 数据加载中显示加载动画
          : DropdownButton<Offices>(
              value: selectedOffice,
              hint: const Text("选择办公地点"),
              onChanged: (Offices? newValue) {
                setState(() {
                  selectedOffice = newValue;
                  // 处理选中后的逻辑,比如打印选中的value
                  print("选中的值:${newValue?.value}");
                });
              },
              items: offices!.map((Offices office) {
                return DropdownMenuItem<Offices>(
                  value: office,
                  child: Text(office.name), // 显示name字段
                );
              }).toList(),
            ),
    ),
  );
}

可选:直接用value作为选项值

如果希望将value字段作为Dropdown的选项值(而非整个Offices对象),可以调整状态变量和组件泛型:

// 修改状态变量
String? selectedValue;

// 生成Dropdown选项时
items: offices!.map((Offices office) {
  return DropdownMenuItem<String>(
    value: office.value,
    child: Text(office.name),
  );
}).toList(),

这样就能实现需求:Dropdown显示DELTA PRIMA、SAMPLE,对应选中值为01、02。

内容的提问来源于stack exchange,提问作者Tsabit

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 05:35:21