Flutter进阶组件(3):SwitchListTile(开关列表项)

 


SwitchListTile是一个包含开关(Switch)的列表项,非常适合用来创建带有标题、副标题以及开关的列表项,常用于设置界面,让用户可以轻松地开启或关闭某个功能。

一、基本使用

SwitchListTile(
  title: const Text('Enable Notifications'),
  value: true, // 开关的初始状态
  onChanged: (bool value) {
    // 开关状态改变时调用的回调
    debugPrint('Enable Notifications is now $value');
  },
)

二、属性

SwitchListTile组件提供了以下属性,以支持各种自定义需求:

  • title: 显示的标题,通常是一个Text Widget。
  • subtitle: 显示的副标题,也可以是一个Text Widget。
  • value: 开关的当前状态(开或关)。
  • onChanged: 当开光状态改变时调用的回调函数,返回开关的新状态。
  • activeColor: 开关打开时的颜色。
  • secondary: 显示在标题旁边的Widget,如图标或图片。
  • isThreeLine: 决定是否显示三行文本,如设置为true,则副标题会换行显示。
  • dense: 是否减少列表项的高度,使文字更紧凑。
  • contentPadding: 控制内边距。

三、基本示例

import 'package:flutter/material.dart';

void main() {
  runApp(const MaterialApp(
    debugShowCheckedModeBanner: false,
    home: SwitchListTileExample(),
  ));
}

class SwitchListTileExample extends StatelessWidget {
  const SwitchListTileExample({super.key});
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('SwitchListTile Example'),
      ),
      body: ListView(
        children: <Widget>[
          SwitchListTile(
            title: const Text('Enable Notifications'),
            value: true, // 开关的初始状态
            onChanged: (bool value) {
              // 开关状态改变时调用的回调
              debugPrint('Enable Notifications is now $value');
            },
          ),
        ],
      ),
    );
  }
}

效果图如下所示:

Flutter_switch_A.png


四、高级用法

SwitchListTile可以与图标、副标题等结合使用,创建复杂的列表项:

SwitchListTile(
  title: const Text('Switch with icon and subtitle'),
  subtitle: const Text('This is a subtitle for the switch'),
  secondary: Icon(Icons.report_problem), // 显示在标题旁边的图标
  value: false,
  onChanged: (bool value) {
    // 处理开关状态改变的逻辑
  },
  isThreeLine: true, // 显示三行文本
)

五、与ListView结合使用

SwitchListTile通常与ListView结合使用,创建滚动的开关列表:

ListView(
  children: <Widget>[
    SwitchListTile(
      title: Text('Option 1'),
      value: false,
      onChanged: (bool value) {
        // 处理开关状态改变的逻辑
      },
    ),
    // 更多的SwitchListTile...
  ],
)

六、自定义SwitchListTile

你可以通过设置不同的属性来定制SwitchListTile的外观:

SwitchListTile(
  title: Text('Custom SwitchListTile'),
  subtitle: Text('This is a custom subtitle'),
  value: false,
  onChanged: (bool value) {
    // 处理点击事件
  },
  activeColor: Colors.green, // 开关激活时的颜色
  contentPadding: EdgeInsets.all(12.0), // 自定义内边距
)

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