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

Flutter实现下拉选择后显示指定文本框的方法咨询

Flutter下拉菜单选择后显示提示框实现方案

下面是可直接运行的完整代码,完全匹配你的需求:

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Dropdown Alert Demo',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const DropdownAlertPage(),
    );
  }
}

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

  @override
  State<DropdownAlertPage> createState() => _DropdownAlertPageState();
}

class _DropdownAlertPageState extends State<DropdownAlertPage> {
  // 跟踪下拉菜单选中项
  String? _selectedItem;
  // 下拉菜单选项列表
  final List<String> _foodOptions = ['汉堡', '蔬菜', '水果'];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('食物选择示例')),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 20),
          child: DropdownButton<String>(
            value: _selectedItem,
            hint: const Text('请选择食物类型'),
            isExpanded: true,
            items: _foodOptions.map((option) {
              return DropdownMenuItem(
                value: option,
                child: Text(option),
              );
            }).toList(),
            onChanged: (value) {
              setState(() {
                _selectedItem = value;
              });
              // 选中汉堡时弹出提示框
              if (value == '汉堡') {
                _showTipDialog();
              }
            },
          ),
        ),
      ),
    );
  }

  // 弹出提示框的方法
  void _showTipDialog() {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          content: const Text('Do not eat that much.'),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('确定'),
            ),
          ],
        );
      },
    );
  }
}

核心逻辑说明:

  • 状态跟踪:用_selectedItem变量记录用户选中的下拉选项,通过setState更新界面状态
  • 下拉菜单配置:DropdownButton通过items生成选项列表,onChanged回调处理选择事件
  • 提示框触发:在选择事件中判断选中项为「汉堡」时,调用_showTipDialog弹出提示
  • 弹窗关闭:点击「确定」按钮通过Navigator.pop关闭弹窗

你可以直接将这段代码复制到Flutter项目中运行,如需修改提示文本或选项内容,直接调整对应字符串即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 12:33:19