Flutter进阶组件(3):SwitchListTile(开关列表项)
SwitchListTile是一个包含开关(Switch)的列表项,非常适合用来创建带有标题、副标题以及开关的列表项,常用于设置界面,让用户可以轻松地开启或关闭某个功能。
一、基本使用
SwitchListTile(
title: const Text('Enable Notifications'),
value: true, // 开关的初始状态
onChanged: (bool value) {
// 开关状态改变时调用的回调
debugPrint('Enable Notifications is now $value');
},
)
二、属性
SwitchListTile组件提供了以下属性,以支持各种自定义需求:
title: 显示的标题,通常是一个TextWidget。subtitle: 显示的副标题,也可以是一个TextWidget。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');
},
),
],
),
);
}
}
效果图如下所示:

四、高级用法
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), // 自定义内边距
)

浙公网安备 33010602011771号