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

Flutter如何将API返回的列表数据嵌入DropdownButton下拉框中

Flutter 接口数据适配DropdownButton实现方案

下面是修改后的完整可运行代码,核心逻辑是将原ListView的渲染逻辑替换为DropdownButton的子项生成逻辑:

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class ApiFipePage extends StatefulWidget {
  const ApiFipePage({super.key});

  @override
  State<ApiFipePage> createState() => _ApiFipePageState();
}

class _ApiFipePageState extends State<ApiFipePage>{
  // 存储当前选中的品牌数据
  dynamic? _selectedMarca;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: FutureBuilder<dynamic>(
          future: pegarUsuarios(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              // 替换原ListView为DropdownButton组件
              return DropdownButton<dynamic>(
                value: _selectedMarca,
                hint: const Text("请选择汽车品牌"),
                // 遍历接口返回的所有品牌生成下拉选项
                items: snapshot.data!.map<DropdownMenuItem<dynamic>>((marca) {
                  return DropdownMenuItem(
                    value: marca,
                    child: Text(marca['nome']),
                  );
                }).toList(),
                // 选中选项后更新页面状态
                onChanged: (value) {
                  setState(() {
                    _selectedMarca = value;
                  });
                  // 需要处理选中逻辑可在这里扩展,比如获取选中品牌的编码
                  debugPrint("选中的品牌编码:${_selectedMarca?['codigo']}");
                },
              );
            } else if (snapshot.hasError) {
              return Center(
                child: Text('${snapshot.error}'),
              );
            }
            return const Center(
              child: CircularProgressIndicator(),
            );
          },
        ),
      ),
    );
  }

  pegarUsuarios() async {
    var url = Uri.parse('https://parallelum.com.br/fipe/api/v1/carros/marcas');
    var resposta = await http.get(url);
    if (resposta.statusCode == 200) {
      return jsonDecode(resposta.body);
    } else {
      throw Exception('não foi possivel carregar os usuarios');
    }
  }
}

核心改动说明

  • 新增_selectedMarca变量存储当前选中的下拉项,适配DropdownButton的受控状态要求
  • 原ListView的遍历逻辑迁移到DropdownButton的items属性中,把每一条接口返回的品牌数据转换成DropdownMenuItem组件
  • 新增onChanged回调,选中选项时调用setState更新页面状态,同步显示选中的内容

如果需要获取选中项的信息,直接从_selectedMarca变量中取值即可,比如获取品牌名称用_selectedMarca?['nome'],获取品牌编码用_selectedMarca?['codigo']。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 13:54:05