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

Flutter新手求助:基于键值对实现DropdownButton并获取选中项的键

嘿,作为Flutter新手碰到这个问题太正常啦!其实根本不用找额外插件,原生的DropdownButton就能完美实现你的需求,我给你拆解两种常用的实现方式:

方法一:直接用Map存储键值对

如果你的键值对比较简单,直接用Map来存储就足够了,核心思路是把键作为DropdownMenuItem的value,这样选中时就能直接拿到键:

import 'package:flutter/material.dart';

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

  @override
  State<KeyValueDropdown> createState() => _KeyValueDropdownState();
}

class _KeyValueDropdownState extends State<KeyValueDropdown> {
  // 存储选中的键
  String? selectedKey;
  // 定义键值对列表
  final Map<String, String> dropdownItems = {
    'product_001': '手机',
    'product_002': '电脑',
    'product_003': '平板',
  };

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('键值对下拉选择')),
      body: Center(
        child: DropdownButton<String>(
          value: selectedKey,
          hint: const Text('请选择商品'),
          // 选中时触发,直接拿到键
          onChanged: (String? newKey) {
            setState(() {
              selectedKey = newKey;
              // 这里就可以处理选中的键了,比如打印或传给其他逻辑
              if (newKey != null) {
                print('选中的商品ID: $newKey');
              }
            });
          },
          // 将Map的键值对转成DropdownMenuItem
          items: dropdownItems.entries.map((entry) {
            return DropdownMenuItem<String>(
              value: entry.key, // 把键作为value传递
              child: Text(entry.value), // 界面显示值
            );
          }).toList(),
        ),
      ),
    );
  }
}
方法二:自定义类(扩展性更强)

如果你的键值对需要附带更多信息(比如图标、描述),自定义一个数据类会更灵活:

import 'package:flutter/material.dart';

// 自定义下拉项类,包含键和显示值,可扩展其他属性
class DropdownOption {
  final String key;
  final String displayText;
  final IconData? icon; // 扩展属性:图标

  DropdownOption({
    required this.key,
    required this.displayText,
    this.icon,
  });
}

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

  @override
  State<CustomDropdown> createState() => _CustomDropdownState();
}

class _CustomDropdownState extends State<CustomDropdown> {
  DropdownOption? selectedOption;
  // 自定义选项列表
  final List<DropdownOption> options = [
    DropdownOption(key: 'user_101', displayText: '张三', icon: Icons.person),
    DropdownOption(key: 'user_102', displayText: '李四', icon: Icons.person),
    DropdownOption(key: 'user_103', displayText: '王五', icon: Icons.person),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('自定义下拉选择')),
      body: Center(
        child: DropdownButton<DropdownOption>(
          value: selectedOption,
          hint: const Text('选择用户'),
          onChanged: (DropdownOption? option) {
            setState(() {
              selectedOption = option;
              if (option != null) {
                print('选中的用户ID: ${option.key}');
                // 还能拿到其他属性,比如图标
                print('用户图标: ${option.icon}');
              }
            });
          },
          items: options.map((option) {
            return DropdownMenuItem<DropdownOption>(
              value: option, // 传递整个自定义对象
              child: Row(
                children: [
                  if (option.icon != null) Icon(option.icon),
                  const SizedBox(width: 8),
                  Text(option.displayText),
                ],
              ),
            );
          }).toList(),
        ),
      ),
    );
  }
}

两种方式都能轻松获取选中项的键,自定义类的方式更适合后续功能扩展。试试上面的代码,应该就能解决你的问题啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:01:21