Flutter进阶组件(4):CupertinoSwitch(iOS 风格开关)

 


在 Flutter 的Cupertino组件库中,CupertinoSwitch是一个用于创建 iOS 风格开关控件的 widget。它提供了一个简洁的滑动开关,允许用户在开启和关闭状态之间进行切换。

一、基本使用

CupertinoSwitch是 Flutter 的 cupertino 库的一部分,因此不需要添加额外的依赖。只需导入 cupertino.dart即可使用:

import 'package:flutter/cupertino.dart';

使用CupertinoSwitch的基本方式如下:

// ignore_for_file: prefer_const_constructors
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';

void main() {
  runApp(const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: ExpansionTilePage(),
      )));
}

class ExpansionTilePage extends StatefulWidget {
  const ExpansionTilePage({super.key});
  @override
  State<ExpansionTilePage> createState() => CupertinoSwitchExample();
}

class CupertinoSwitchExample extends State<ExpansionTilePage> {
  bool _switchValue = false;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: CupertinoPageScaffold(
        navigationBar: CupertinoNavigationBar(
          middle: Text('CupertinoSwitch Example'),
        ),
        child: Center(
          child: CupertinoSwitch(
            value: _switchValue,
            onChanged: (value) {
              setState(() {
                _switchValue = value;
              });
            },
          ),
        ),
      ),
    );
  }
}

在这个例子中,我们创建了一个简单的 iOS 风格开关,并在状态变化时更新_switchValue。效果图如下图所示:

Flutter_switch_B.png


二、属性

CupertinoSwitch小部件的主要属性包括:

  • value: 开关的当前状态,true表示开启,false表示关闭。
  • onChanged: 当开关状态改变时调用的回调函数。
  • activeColor: 开关处于开启状态时的背景颜色。

三、自定义 CupertinoSwitch

CupertinoSwitch可以用于各种自定义场景,例如:

CupertinoSwitch(
  value: _switchValue,
  onChanged: (value) {
    setState(() {
      _switchValue = value;
    });
  },
  thumbColor: Color.fromARGB(255, 1, 29, 53), // 滑块颜色
  activeColor: Colors.blue, // 滑块打开后的颜色
  trackColor: Colors.grey, // 轨道颜色            
)

posted @   fengMisaka  阅读(69)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· 【.NET】调用本地 Deepseek 模型
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
历史上的今天:
2019-12-26 Qt 使用 MPV 开源播放器
点击右上角即可分享
微信分享提示