字
字节笔记本
2026年2月22日
OpenIM Flutter SwitchButton 组件解析
本文介绍 OpenIM Flutter Demo 中的 SwitchButton 组件,一个简洁实用的开关按钮实现。该组件通过 GestureDetector 和 Image 组合,提供了直观的开关状态切换功能。
组件概述
SwitchButton 是一个无状态组件(StatelessWidget),用于在 Flutter 应用中显示可切换的开关状态。它支持自定义尺寸和点击回调,适用于设置页面、功能开关等场景。
源码解析
dart
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:openim_demo/src/res/images.dart';
class SwitchButton extends StatelessWidget {
const SwitchButton({
Key? key,
this.on = true,
this.onTap,
this.width,
this.height,
}) : super(key: key);
final bool on;
final Function()? onTap;
final double? width;
final double? height;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onTap,
child: Container(
child: Image.asset(
on ? ImageRes.ic_switchOn : ImageRes.ic_switchOff,
width: width ?? 38.w,
height: height ?? 22.h,
),
),
);
}
}参数说明
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
on | bool | true | 开关状态,true 为开启,false 为关闭 |
onTap | Function()? | null | 点击回调函数 |
width | double? | 38.w | 按钮宽度,使用 ScreenUtil 适配 |
height | double? | 22.h | 按钮高度,使用 ScreenUtil 适配 |
核心实现
1. 状态显示
组件通过 on 参数控制显示的图片资源:
on == true:显示ImageRes.ic_switchOn(开启状态图片)on == false:显示ImageRes.ic_switchOff(关闭状态图片)
2. 点击交互
使用 GestureDetector 包裹 Container,通过 onTap 回调实现点击切换功能。
3. 尺寸适配
使用 flutter_screenutil 进行屏幕适配:
- 默认宽度:
38.w(38逻辑像素) - 默认高度:
22.h(22逻辑像素)
使用示例
基础用法
dart
SwitchButton(
on: true,
onTap: () {
print('开关被点击');
},
)自定义尺寸
dart
SwitchButton(
on: isEnabled,
width: 50.w,
height: 30.h,
onTap: () {
setState(() {
isEnabled = !isEnabled;
});
},
)在设置页面中使用
dart
class SettingsPage extends StatefulWidget {
@override
_SettingsPageState createState() => _SettingsPageState();
}
class _SettingsPageState extends State<SettingsPage> {
bool _notificationEnabled = true;
bool _soundEnabled = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('设置')),
body: ListView(
children: [
ListTile(
title: Text('消息通知'),
trailing: SwitchButton(
on: _notificationEnabled,
onTap: () {
setState(() {
_notificationEnabled = !_notificationEnabled;
});
},
),
),
ListTile(
title: Text('声音提醒'),
trailing: SwitchButton(
on: _soundEnabled,
onTap: () {
setState(() {
_soundEnabled = !_soundEnabled;
});
},
),
),
],
),
);
}
}依赖说明
该组件依赖以下包:
yaml
dependencies:
flutter_screenutil: ^5.0.0 # 屏幕适配项目背景
OpenIM Flutter Demo 是基于开源 OpenIM SDK 开发的即时通讯应用示例,提供了完整的 IM 功能实现,包括:
- 账号系统(手机/邮箱注册登录)
- 好友管理(添加、删除、黑名单)
- 群组功能(创建、邀请、转让群主)
- 消息系统(文本、图片、语音、视频等)
- 音视频通话
SwitchButton 作为其中的 UI 组件之一,为设置页面等功能开关提供了简洁的实现方案。
项目链接
- GitHub 仓库:https://github.com/OpenIMSDK/Open-IM-Flutter-Demo
- OpenIM 官网:https://www.openim.io
- 官方文档:https://docs.openim.io
分享: