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

Flutter中如何用跨平台适配组件替代CupertinoSwitch?

有,Flutter 自带 Switch.adaptive 就是你要的跨平台适配开关组件

这个组件和 showAdaptiveDialog 逻辑完全一致:

  • 在 iOS 和 macOS 上自动渲染成 CupertinoSwitch 的样式
  • 在 Android、Windows 等其他平台则使用 Material 风格的 Switch

直接把你代码里的 CupertinoSwitch 替换成 Switch.adaptive 即可,不需要额外判断平台,修改后的示例代码如下:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:note_app/theme/theme_provider.dart';
import 'package:provider/provider.dart';

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).colorScheme.background,
      appBar: AppBar(
        elevation: 0,
        backgroundColor: Colors.transparent,
        foregroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: Row(
        children: [
          //dark mode
          Text("Dark Mode"),

          // 替换为自适应开关
          Switch.adaptive(
            value: Provider.of<ThemeProvider>(context, listen: false).isDarkMode,
            onChanged: (value) =>
                Provider.of<ThemeProvider>(context, listen: false)
                    .toggleTheme(),
          )
        ],
      ),
    );
  }
}

如果需要对不同平台的样式做更细致的自定义,可以结合 Theme 或者 CupertinoTheme 调整,但 Switch.adaptive 已经能满足绝大多数跨平台适配需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 09:37:04