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

如何在Flutter中创建Alert Dialog内的Toggle List组件

Flutter 实现 Alert Dialog 内的切换列表

你可以通过 AlertDialog 结合 SwitchListTile 组件快速实现这种嵌入在弹窗里的切换列表效果,以下是完整的实现代码:

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(
      home: Scaffold(
        appBar: AppBar(title: const Text("Toggle List in Dialog")),
        body: const Center(child: ToggleDialogDemo()),
      ),
    );
  }
}

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

  @override
  State<ToggleDialogDemo> createState() => _ToggleDialogDemoState();
}

class _ToggleDialogDemoState extends State<ToggleDialogDemo> {
  // 维护每个选项的开关状态
  final Map<String, bool> _toggleStates = {
    "Option 1": false,
    "Option 2": true,
    "Option 3": false,
    "Option 4": true,
  };

  void _showToggleDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text("Select Options"),
        // 用ListView包裹多个SwitchListTile,避免内容溢出
        content: SizedBox(
          width: double.maxFinite,
          child: ListView(
            shrinkWrap: true,
            children: _toggleStates.entries.map((entry) {
              return SwitchListTile(
                title: Text(entry.key),
                value: entry.value,
                onChanged: (newValue) {
                  setState(() {
                    _toggleStates[entry.key] = newValue;
                  });
                },
              );
            }).toList(),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text("Cancel"),
          ),
          TextButton(
            onPressed: () {
              // 这里可以处理确认后的逻辑,比如获取选中的选项
              Navigator.pop(context);
            },
            child: const Text("OK"),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: _showToggleDialog,
      child: const Text("Show Toggle Dialog"),
    );
  }
}

关键说明:

  • 使用 SwitchListTile 组件:自带左侧标题、右侧开关的布局,完美匹配需求中的列表项样式
  • 状态管理:用 Map 存储每个选项的开关状态,通过 setState 更新UI
  • 弹窗内容处理:用 ListView + shrinkWrap: true 确保列表自适应内容高度,避免弹窗内容溢出
  • 弹窗操作按钮:添加Cancel和OK按钮,可在OK按钮的回调中处理选中状态的提交逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 14:05:16