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

Flutter中选择DropdownButton指定选项时禁用TextField的实现方法

Flutter实现DropdownButton与TextField联动

核心思路是通过状态变量跟踪DropdownButton的选中值,以此动态控制TextField的启用状态和内容。以下是完整实现代码:

import 'package:flutter/material.dart';

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

  @override
  State<InsuranceForm> createState() => _InsuranceFormState();
}

class _InsuranceFormState extends State<InsuranceForm> {
  // 保存选中的保险类型
  String? _selectedInsurance;
  // 控制TextField的文本内容
  final TextEditingController _textFieldController = TextEditingController();

  // 下拉选项列表(复用你提供的代码)
  List<DropdownMenuItem<String>> get dropdownSelected {
    return [
      const DropdownMenuItem(
        value: "LION",
        child: Text("Lion Insurance"),
      ),
      const DropdownMenuItem(
        value: "General",
        child: Text("General Insurance"),
      ),
    ];
  }

  @override
  void dispose() {
    // 销毁控制器避免内存泄漏
    _textFieldController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Insurance Form")),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            DropdownButton<String>(
              value: _selectedInsurance,
              hint: const Text("Select Insurance Type"),
              items: dropdownSelected,
              onChanged: (String? newValue) {
                setState(() {
                  _selectedInsurance = newValue;
                  // 根据选中项更新TextField
                  if (newValue == "General") {
                    // 选中General时,填充"-"并禁用
                    _textFieldController.text = "-";
                  } else {
                    // 可选:切换回Lion时清空文本,或保留用户之前输入
                    // _textFieldController.clear();
                  }
                });
              },
            ),
            const SizedBox(height: 16),
            TextField(
              controller: _textFieldController,
              // 只有选中LION时才启用输入
              enabled: _selectedInsurance != "General",
              decoration: const InputDecoration(
                border: OutlineInputBorder(),
                labelText: "Enter Details",
              ),
            ),
          ],
        ),
      ),
    );
  }
}

关键逻辑说明:

  • _selectedInsurance作为状态变量,实时同步DropdownButton的选中值
  • 下拉选项的onChanged回调中,更新状态的同时,根据选中值设置TextField的文本内容
  • TextField的enabled属性通过_selectedInsurance != "General"动态控制,实现选中General时禁用输入的效果
  • 使用TextEditingController统一管理TextField的文本,确保切换选项时内容自动更新

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 23:15:33