Flutter 多功能列表项:图标、文字与Switch组合
下面是一个完整的实现,包含左边图标、中间标题和右边 Switch 的组件,背景为白色:
完整组件代码
import 'package:flutter/material.dart';class IconTitleSwitch extends StatelessWidget {final IconData icon;final String title;final bool value;final ValueChanged<bool> onChanged;final Color iconColor;final Color? backgroundColor;final EdgeInsetsGeometry padding;const IconTitleSwitch({Key? key,required this.icon,required this.title,required this.value,required this.onChanged,this.iconColor = Colors.blue,this.backgroundColor = Colors.white,this.padding = const EdgeInsets.symmetric(horizontal: 16, vertical: 12),}) : super(key: key);Widget build(BuildContext context) {return Container(color: backgroundColor,padding: padding,child: Row(children: [// 左侧图标Icon(icon,color: iconColor,size: 24,),const SizedBox(width: 16),// 中间标题(自动扩展)Expanded(child: Text(title,style: const TextStyle(fontSize: 16,color: Colors.black,),),),// 右侧SwitchSwitch(value: value,onChanged: onChanged,activeColor: Colors.blue,),],),);}
}
使用示例
class ExamplePage extends StatefulWidget {const ExamplePage({Key? key}) : super(key: key); _ExamplePageState createState() => _ExamplePageState();
}class _ExamplePageState extends State<ExamplePage> {bool _notificationEnabled = true;bool _darkModeEnabled = false;bool _autoUpdateEnabled = true;Widget build(BuildContext context) {return Scaffold(appBar: AppBar(title: const Text('设置'),),body: Column(children: [// 使用示例1IconTitleSwitch(icon: Icons.notifications,title: '消息通知',value: _notificationEnabled,onChanged: (value) {setState(() {_notificationEnabled = value;});},),// 分割线const Divider(height: 1),// 使用示例2IconTitleSwitch(icon: Icons.dark_mode,title: '夜间模式',value: _darkModeEnabled,onChanged: (value) {setState(() {_darkModeEnabled = value;});},iconColor: Colors.purple,),// 分割线const Divider(height: 1),// 使用示例3IconTitleSwitch(icon: Icons.system_update,title: '自动更新',value: _autoUpdateEnabled,onChanged: (value) {setState(() {_autoUpdateEnabled = value;});},iconColor: Colors.green,),],),);}
}
组件特性说明
- 可定制属性:
· icon: 左侧显示的图标
· title: 中间显示的标题文本
· value: Switch 的当前值
· onChanged: Switch 状态改变回调
· iconColor: 图标颜色(默认蓝色)
· backgroundColor: 背景颜色(默认白色)
· padding: 内边距(默认水平16,垂直12) - 布局特点:
· 使用 Row 水平排列图标、标题和 Switch
· 标题使用 Expanded 自动填充可用空间
· 默认添加白色背景
· 组件高度自适应内容 - 扩展建议:
· 如果需要添加副标题,可以在 Text 下方添加一个 Text 小部件
· 如果需要圆角背景,可以给 Container 添加 borderRadius
· 如果需要点击整个区域的效果,可以用 InkWell 包裹
效果预览
这个组件会呈现如下效果:
[图标] 标题文本 [Switch]
所有元素排列在一行,左侧为图标,中间为标题(自动扩展填充空间),右侧为 Switch 开关,整个组件背景为白色。