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

Flutter中Dropdown组件传递的字符串值无法同步更新的问题咨询

解决方案

问题出在自定义Dropdown组件未将内部值的变化通知给父组件,导致父组件的sourceCity和destenationCity无法同步更新。通过回调函数即可实现父子组件的状态同步,具体修改如下:

1. 修改自定义Dropdown组件(DropDown.dart)

给Dropdown类添加回调参数,用于将选中的值传递回父组件:

class Dropdown extends StatefulWidget{
  final List<String> items;
  final String hint;
  final Color backgroundColor;
  final Color iconColor;
  final Color textColor;
  final double fontSize;
  final ValueChanged<String>? onChanged; // 新增回调参数

  Dropdown(
    this.hint,
    this.backgroundColor,
    this.iconColor,
    this.textColor,
    this.fontSize, {
    super.key,
    required this.items,
    this.onChanged, // 构造函数添加回调
  });

  @override
  State<StatefulWidget> createState() => DropdownState();
}

class DropdownState extends State<Dropdown>{
  late String selectedValue;

  @override
  void initState() {
    super.initState();
    selectedValue = widget.hint; // 用selectedValue管理选中状态,语义更清晰
  }

  @override
  Widget build(BuildContext context) {
    return Theme(
      data: Theme.of(context).copyWith(
        canvasColor: widget.backgroundColor,
      ),
      child: DropdownButton<String>(
        value: selectedValue, // 绑定选中值
        icon: Icon(Icons.arrow_drop_down, color: widget.iconColor),
        elevation: 16,
        style: TextStyle(color: widget.textColor),
        underline: Container(
          height: 2,
          width: 50,
          color: Colors.white,
        ),
        onChanged: (String? newValue) {
          if (newValue == null) return;
          setState(() {
            selectedValue = newValue;
          });
          widget.onChanged?.call(newValue); // 调用回调传递新值给父组件
        },
        items: widget.items
            .map<DropdownMenuItem<String>>((String value) {
          return DropdownMenuItem<String>(
            value: value,
            child: Text(value,style: TextStyle(fontSize: widget.fontSize),),
          );
        }).toList(),
      ),
    );
  }
}

2. 修改父组件(add_journey.dart)

给每个Dropdown绑定对应回调,更新父组件的状态变量:

class AddJourneyPage extends StatefulWidget {
  @override
  _AddJourneyPage createState() => _AddJourneyPage();
}

class _AddJourneyPage extends State {
  String sourceCity = 'Source City';
  String destenationCity = 'Destination City';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Dropdown(
            sourceCity,
            Colors.grey.shade200,
            Colors.black,
            Colors.grey.shade700,
            18.0,
            items: ['Aleppo','Damascus','Homs','Hama'],
            onChanged: (value) { // 绑定回调更新sourceCity
              setState(() {
                sourceCity = value;
              });
            },
          ),
          Dropdown(
            destenationCity,
            Colors.grey.shade200,
            Colors.black,
            Colors.grey.shade700,
            18.0,
            items: ['Aleppo','Damascus','Homs','Hama'],
            onChanged: (value) { // 绑定回调更新destenationCity
              setState(() {
                destenationCity = value;
              });
            },
          ),
          ElevatedButton(
            onPressed: ()  {
              print(sourceCity); // 现在会打印选中的城市
              print(destenationCity);
            },
            child: const Text('Add Journey')
          )
        ],
      ),
    );
  }
}

关键说明

  • 子组件通过ValueChanged<String>类型的回调,将选中值传递给父组件;
  • 父组件调用setState更新状态变量,触发UI重建,确保Dropdown显示最新值;
  • 子组件内部用selectedValue管理选中状态,避免与传入的hint参数混淆。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 10:20:43