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

Flutter新手求助:如何实现CupertinoSwitch控制容器显隐

解决CupertinoSwitch控制容器显示/隐藏的问题

核心思路是通过条件渲染,根据开关的状态值_giftwrapping来决定是否展示下方容器。以下是修改后的完整示例代码:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';

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

  @override
  State<GiftWrappingPage> createState() => _GiftWrappingPageState();
}

class _GiftWrappingPageState extends State<GiftWrappingPage> {
  // 初始化开关状态,默认关闭
  bool _giftwrapping = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Text(
                  'Gift Wrapping',
                  style: GoogleFonts.poppins(
                    color: const Color(0xff000000),
                    fontSize: 14,
                    fontWeight: FontWeight.w500,
                    letterSpacing: 0.4,
                  ),
                ),
                const Spacer(), // 替代固定padding,适配不同屏幕宽度
                Transform.scale(
                  scale: 1,
                  child: CupertinoSwitch(
                    value: _giftwrapping,
                    thumbColor: const Color(0xffffffff),
                    activeColor: const Color(0xff6939ed),
                    onChanged: (value) {
                      setState(() {
                        _giftwrapping = value;
                      });
                    },
                  ),
                ),
              ],
            ),
            // 条件渲染:开关打开时显示容器,关闭时隐藏
            if (_giftwrapping)
              Container(
                margin: const EdgeInsets.only(top: 16),
                padding: const EdgeInsets.all(12),
                color: Colors.grey.shade100,
                child: const Text(
                  '礼品包装选项已开启,可选择包装样式',
                  style: TextStyle(fontSize: 13),
                ),
              ),
          ],
        ),
      ),
    );
  }
}

关键说明:

  • 确保_giftwrapping作为State类的成员变量存在,初始值设为false(默认关闭开关)。
  • 使用if (_giftwrapping)的条件语法,只有当开关状态为true时,容器才会被加入Widget树,实现显示/隐藏的动态切换。
  • 原代码中固定left:98的Padding被替换为Spacer(),让开关自动靠右,提升多屏幕适配性。

你也可以用Visibility组件实现相同效果,代码示例:

Visibility(
  visible: _giftwrapping,
  child: Container(
    margin: const EdgeInsets.only(top: 16),
    padding: const EdgeInsets.all(12),
    color: Colors.grey.shade100,
    child: const Text('礼品包装选项已开启,可选择包装样式'),
  ),
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 05:03:12