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

Flutter中自定义DropdownButton组件并获取选中值的实现方法

Flutter 封装可复用的 DropdownButton 并捕获选中值

一、封装自定义可复用 DropdownButton 组件

把下拉框的UI和逻辑抽成独立组件,通过回调函数将选中值传递给父页面。创建CustomDropdown组件:

import 'package:flutter/material.dart';

class CustomDropdown extends StatefulWidget {
  final List items;
  final String? selectedValue;
  final Function(String?) onChanged;

  const CustomDropdown({
    super.key,
    required this.items,
    required this.selectedValue,
    required this.onChanged,
  });

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

class _CustomDropdownState extends State<CustomDropdown> {
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.only(left: 16, right: 16),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.amber),
        borderRadius: BorderRadius.circular(15),
      ),
      child: DropdownButton<String>(
        underline: Container(),
        hint: const Text('选择编号'),
        items: widget.items.map((item) {
          return DropdownMenuItem(
            value: item['ClassCode'].toString(),
            child: Text(
              item['ClassName'].toString(),
              style: const TextStyle(color: Colors.amber, fontSize: 16),
            ),
          );
        }).toList(),
        onChanged: widget.onChanged,
        value: widget.selectedValue,
        isExpanded: true, // 让下拉框占满容器宽度
      ),
    );
  }
}

二、在主页面使用自定义组件并捕获选中值

修改MyHomePage,引入自定义组件,通过回调维护选中状态,实现打印功能:

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_application_1/Models/cachdata.dart';
import 'package:flutter_application_1/uti/themes.dart';
import 'package:http/http.dart' as http;
// 导入自定义组件
import 'custom_dropdown.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  CacheData.cacheInitialization();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: Themes.light,
      home: const MyHomePage(title: "test"),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List categoryItemlist = [];
  String? dropdownvalue;

  Future getAllCategory() async {
    var baseUrl = "https://gssskhokhar.com/api/classes/";
    http.Response response = await http.get(Uri.parse(baseUrl));
    if (response.statusCode == 200) {
      var jsonData = json.decode(response.body);
      setState(() {
        categoryItemlist = jsonData;
      });
    }
  }

  @override
  void initState() {
    super.initState();
    getAllCategory();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("DropDown List"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CustomDropdown(
              items: categoryItemlist,
              selectedValue: dropdownvalue,
              onChanged: (newVal) {
                setState(() {
                  dropdownvalue = newVal;
                });
              },
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                print("选中值: $dropdownvalue");
                // 可选:用弹窗显示选中值
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text("选中值: $dropdownvalue")),
                );
              },
              child: const Text("打印下拉框选中值"),
            ),
          ],
        ),
      ),
    );
  }
}

关键说明

  • 自定义组件通过onChanged回调将选中值传递给父组件,父组件负责维护选中状态,解决了之前无法捕获值的问题。
  • 添加isExpanded: true让下拉框适配容器宽度,优化UI显示。
  • 明确dropdownvalue类型为String?,避免类型匹配问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 11:25:09