【完结】Flutter3+Getx仿微信桌面端exe聊天程序
wptr33 2024-12-05 17:01 17 浏览
继上一篇基于Flutter3.x桌面端仿微信exe实例一经发表,被赞爆了。
今天再来分享一些实现的技术知识,希望以下分享对大家有些许的帮助~~
技术框架
- 开发工具:vscode
- 窗口管理:bitsdojo_window: ^0.1.6
- 托盘管理:system_tray: ^2.0.3
- 路由/状态管理:get: ^4.6.6
- 本地存储:get_storage: ^2.1.1
- 图片预览插件:photo_view: ^0.14.0
- 网址预览:url_launcher: ^6.2.4
- 视频组件:media_kit: ^1.1.10+1
- 文件选择器:file_picker: ^6.1.1
已经实现了聊天消息、通讯录、收藏、朋友圈、短视频、我的等页面模块。
项目结构目录
// 创建flutter项目模板
flutter create win_proj
// 运行到桌面
flutter run -d windows
注意:开发之前需要自行配置好flutter sdk和dart sdk环境。
https://flutter.dev/
https://www.dartcn.com/
整体采用 bitsdojo_window 插件进行窗口管理。支持自定义窗口尺寸及系统操作按钮(最大化/最小化/关闭)。
https://pub-web.flutter-io.cn/packages/bitsdojo_window
flutter桌面端通过 system_tray 插件,生成系统托盘图标。
https://pub-web.flutter-io.cn/packages/system_tray
main.dart入口配置
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:bitsdojo_window/bitsdojo_window.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:media_kit/media_kit.dart';
import 'package:system_tray/system_tray.dart';
import 'utils/index.dart';
// 引入公共样式
import 'styles/index.dart';
// 引入公共布局模板
import 'layouts/index.dart';
// 引入路由配置
import 'router/index.dart';
void main() async {
// 初始化get_storage存储类
await GetStorage.init();
// 初始化media_kit视频套件
WidgetsFlutterBinding.ensureInitialized();
MediaKit.ensureInitialized();
initSystemTray();
runApp(const MyApp());
// 初始化bitsdojo_window窗口
doWhenWindowReady(() {
appWindow.size = const Size(850, 620);
appWindow.minSize = const Size(700, 500);
appWindow.alignment = Alignment.center;
appWindow.title = 'Flutter3-WinChat';
appWindow.show();
});
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return GetMaterialApp(
title: 'FLUTTER3 WINCHAT',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primaryColor: FStyle.primaryColor,
useMaterial3: true,
// 修正windows端字体粗细不一致
fontFamily: Platform.isWindows ? 'Microsoft YaHei' : null,
),
home: const Layout(),
// 初始路由
initialRoute: Utils.isLogin() ? '/index' :'/login',
// 路由页面
getPages: routes,
onInit: () {},
onReady: () {},
);
}
}
// 创建系统托盘图标
Future<void> initSystemTray() async {
String trayIco = 'assets/images/tray.ico';
SystemTray systemTray = SystemTray();
// 初始化系统托盘
await systemTray.initSystemTray(
title: 'system-tray',
iconPath: trayIco,
);
// 右键菜单
final Menu menu = Menu();
await menu.buildFrom([
MenuItemLabel(label: 'show', onClicked: (menuItem) => appWindow.show()),
MenuItemLabel(label: 'hide', onClicked: (menuItem) => appWindow.hide()),
MenuItemLabel(label: 'close', onClicked: (menuItem) => appWindow.close()),
]);
await systemTray.setContextMenu(menu);
// 右键事件
systemTray.registerSystemTrayEventHandler((eventName) {
debugPrint('eventName: $eventName');
if (eventName == kSystemTrayEventClick) {
Platform.isWindows ? appWindow.show() : systemTray.popUpContextMenu();
} else if (eventName == kSystemTrayEventRightClick) {
Platform.isWindows ? systemTray.popUpContextMenu() : appWindow.show();
}
});
}
flutter自定义右上角操作按钮组
@override
Widget build(BuildContext context){
return Row(
children: [
Container(
child: widget.leading,
),
Visibility(
visible: widget.minimizable,
child: MouseRegion(
cursor: SystemMouseCursors.click,
child: SizedBox(
width: 32.0,
height: 36.0,
child: MinimizeWindowButton(colors: buttonColors, onPressed: handleMinimize,),
)
),
),
Visibility(
visible: widget.maximizable,
child: MouseRegion(
cursor: SystemMouseCursors.click,
child: SizedBox(
width: 32.0,
height: 36.0,
child: isMaximized ?
RestoreWindowButton(colors: buttonColors, onPressed: handleMaxRestore,)
:
MaximizeWindowButton(colors: buttonColors, onPressed: handleMaxRestore,),
),
),
),
Visibility(
visible: widget.closable,
child: MouseRegion(
cursor: SystemMouseCursors.click,
child: SizedBox(
width: 32.0,
height: 36.0,
child: CloseWindowButton(colors: closeButtonColors, onPressed: handleExit,),
),
),
),
Container(
child: widget.trailing,
),
],
);
}
// 最小化
void handleMinimize() {
appWindow.minimize();
}
// 设置最大化/恢复
void handleMaxRestore() {
appWindow.maximizeOrRestore();
}
// 关闭
void handleExit() {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
content: const Text('是否最小化至托盘,不退出程序?', style: TextStyle(fontSize: 16.0),),
backgroundColor: Colors.white,
surfaceTintColor: Colors.white,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(3.0)),
elevation: 3.0,
actionsPadding: const EdgeInsets.all(15.0),
actions: [
TextButton(
onPressed: () {
Get.back();
appWindow.close();
},
child: const Text('退出', style: TextStyle(color: Colors.red),)
),
TextButton(
onPressed: () {
Get.back();
appWindow.hide();
},
child: const Text('最小化至托盘', style: TextStyle(color: Colors.deepPurple),)
),
],
);
}
);
}
通过flutter内置的WidgetsBindingObserver来监测窗口变化。
class _WinbtnState extends State<Winbtn> with WidgetsBindingObserver {
// 是否最大化
bool isMaximized = false;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
// 监听窗口尺寸变化
@override
void didChangeMetrics() {
super.didChangeMetrics();
WidgetsBinding.instance.addPostFrameCallback((_) {
setState(() {
isMaximized = appWindow.isMaximized;
});
});
}
// ...
}
flutter布局模板
项目整体参照微信客户端,分为如下几个大模块。
class Layout extends StatefulWidget {
const Layout({
super.key,
this.activitybar = const Activitybar(),
this.sidebar,
this.workbench,
this.showSidebar = true,
});
final Widget? activitybar; // 左侧操作栏
final Widget? sidebar; // 侧边栏
final Widget? workbench; // 右侧工作面板
final bool showSidebar; // 是否显示侧边栏
@override
State<Layout> createState() => _LayoutState();
}
return Scaffold(
backgroundColor: Colors.grey[100],
body: Flex(
direction: Axis.horizontal,
children: [
// 左侧操作栏
MoveWindow(
child: widget.activitybar,
onDoubleTap: () => {},
),
// 侧边栏
Visibility(
visible: widget.showSidebar,
child: SizedBox(
width: 270.0,
child: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
Color(0xFFEEEBE7), Color(0xFFEEEEEE)
]
),
),
child: widget.sidebar,
),
),
),
// 主体容器
Expanded(
child: Column(
children: [
WindowTitleBarBox(
child: Row(
children: [
Expanded(
child: MoveWindow(),
),
// 右上角操作按钮组
Winbtn(
leading: Row(
children: [
IconButton(onPressed: () {}, icon: const Icon(Icons.auto_fix_high), iconSize: 14.0,),
IconButton(
onPressed: () {
setState(() {
winTopMost = !winTopMost;
});
},
tooltip: winTopMost ? '取消置顶' : '置顶',
icon: const Icon(Icons.push_pin_outlined),
iconSize: 14.0,
highlightColor: Colors.transparent, // 点击水波纹颜色
isSelected: winTopMost ? true : false, // 是否选中
style: ButtonStyle(
visualDensity: VisualDensity.compact,
backgroundColor: MaterialStateProperty.all(winTopMost ? Colors.grey[300] : Colors.transparent),
shape: MaterialStatePropertyAll(
RoundedRectangleBorder(borderRadius: BorderRadius.circular(0.0))
),
),
),
],
),
),
],
),
),
// 右侧工作面板
Expanded(
child: Container(
child: widget.workbench,
),
),
],
),
),
],
),
);
@override
Widget build(BuildContext context) {
return Container(
width: 54.0,
decoration: const BoxDecoration(
color: Color(0xFF2E2E2E),
),
child: NavigationRail(
backgroundColor: Colors.transparent,
labelType: NavigationRailLabelType.none, // all 显示图标+标签 selected 只显示激活图标+标签 none 不显示标签
indicatorColor: Colors.transparent, // 去掉选中椭圆背景
indicatorShape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(0.0),
),
unselectedIconTheme: const IconThemeData(color: Color(0xFF979797), size: 24.0),
selectedIconTheme: const IconThemeData(color: Color(0xFF07C160), size: 24.0,),
unselectedLabelTextStyle: const TextStyle(color: Color(0xFF979797),),
selectedLabelTextStyle: const TextStyle(color: Color(0xFF07C160),),
// 头部(图像)
leading: GestureDetector(
onPanStart: (details) => {},
child: Container(
margin: const EdgeInsets.only(top: 30.0, bottom: 10.0),
child: InkWell(
child: Image.asset('assets/images/avatar/uimg1.jpg', height: 36.0, width: 36.0,),
onTapDown: (TapDownDetails details) {
cardDX = details.globalPosition.dx;
cardDY = details.globalPosition.dy;
},
onTap: () {
showCardDialog(context);
},
),
),
),
// 尾部(链接)
trailing: Expanded(
child: Container(
margin: const EdgeInsets.only(bottom: 10.0),
child: GestureDetector(
onPanStart: (details) => {},
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
IconButton(icon: Icon(Icons.info_outline, color: Color(0xFF979797), size: 24.0), onPressed:(){showAboutDialog(context);}),
PopupMenuButton(
icon: const Icon(Icons.menu, color: Color(0xFF979797), size: 24.0,),
offset: const Offset(54.0, 0.0),
tooltip: '',
color: const Color(0xFF353535),
surfaceTintColor: Colors.transparent,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(0.0)),
padding: EdgeInsets.zero,
itemBuilder: (BuildContext context) {
return <PopupMenuItem>[
popupMenuItem('我的私密空间', 0),
popupMenuItem('锁定', 1),
popupMenuItem('意见反馈', 2),
popupMenuItem('设置', 3),
];
},
onSelected: (value) {
switch(value) {
case 0:
Get.toNamed('/my');
break;
case 3:
Get.toNamed('/setting');
break;
}
},
),
],
),
),
),
),
selectedIndex: tabCur,
destinations: [
...tabNavs
],
onDestinationSelected: (index) {
setState(() {
tabCur = index;
if(tabRoute[index] != null && tabRoute[index]?['path'] != null) {
Get.toNamed(tabRoute[index]['path']);
}
});
},
),
);
}
flutter3短视频模板
// flutter3短视频模板
Container(
width: MediaQuery.of(context).size.height * 9 / 16,
decoration: const BoxDecoration(
color: Colors.black,
),
child: Stack(
children: [
// Swiper垂直滚动区域
PageView(
// 自定义滚动行为(支持桌面端滑动、去掉滚动条槽)
scrollBehavior: SwiperScrollBehavior().copyWith(scrollbars: false),
scrollDirection: Axis.vertical,
controller: pageController,
onPageChanged: (index) {
// 暂停(垂直滑动)
controller.player.pause();
},
children: [
Stack(
children: [
// 视频区域
Positioned(
top: 0,
left: 0,
right: 0,
bottom: 0,
child: GestureDetector(
child: Stack(
children: [
// 短视频插件
Video(
controller: controller,
fit: BoxFit.cover,
// 无控制条
controls: NoVideoControls,
),
// 播放/暂停按钮
Center(
child: IconButton(
onPressed: () {
controller.player.playOrPause();
},
icon: StreamBuilder(
stream: controller.player.stream.playing,
builder: (context, playing) {
return Visibility(
visible: playing.data == false,
child: Icon(
playing.data == true ? Icons.pause : Icons.play_arrow_rounded,
color: Colors.white70,
size: 50,
),
);
},
),
),
),
],
),
onTap: () {
controller.player.playOrPause();
},
),
),
// 右侧操作栏
Positioned(
bottom: 70.0,
right: 10.0,
child: Column(
children: [
// ...
],
),
),
// 底部信息区域
Positioned(
bottom: 30.0,
left: 15.0,
right: 80.0,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// ...
],
),
),
// 播放mini进度条
Positioned(
bottom: 15.0,
left: 15.0,
right: 15.0,
child: Container(
// ...
),
),
],
),
Container(
color: Colors.black,
child: const Center(child: Text('1', style: TextStyle(color: Colors.white, fontSize: 60),),)
),
Container(
color: Colors.black,
child: const Center(child: Text('2', style: TextStyle(color: Colors.white, fontSize: 60),),)
),
Container(
color: Colors.black,
child: const Center(child: Text('3', style: TextStyle(color: Colors.white, fontSize: 60),),)
),
],
),
// 固定tab菜单
Align(
alignment: Alignment.topCenter,
child: DefaultTabController(
length: 3,
child: TabBar(
tabs: const [
Tab(text: '推荐'),
Tab(text: '关注'),
Tab(text: '同城'),
],
tabAlignment: TabAlignment.center,
overlayColor: MaterialStateProperty.all(Colors.transparent),
unselectedLabelColor: Colors.white70,
labelColor: const Color(0xff0091ea),
indicatorColor: const Color(0xff0091ea),
indicatorSize: TabBarIndicatorSize.label,
dividerHeight: 0,
indicatorPadding: const EdgeInsets.all(5),
),
),
),
],
),
),
flutter_winchat项目涵盖了很多flutter知识点,限于篇幅不能一一详细分享了。
希望以上的分享内容,对小伙伴们有些帮助。
- 上一篇:Flutter——构建界面
- 下一篇:2023 年 Flutter 基础面试题
相关推荐
- 台积电提出SRAM存内计算新方法,能效比可达89TOPS/W
-
芯东西(公众号:aichip001)编译|高歌编辑|云鹏芯东西3月16日消息,近期,台积电的研究人员在ISSCC2021会议上公布了一种改良的SRAM存储器阵列,该SRAM阵列采用22nm工...
- Golang中如何判断两个slice是否相等?
-
在Golang中,要判断两个slice是否相等是不能直接使用==运算符的(==只能说明两个slice是否指向同一个底层数组)。如果两个slice的底层数组相同,但长度或容量不同...
- JS入门基础知识(js基础知识总结笔记)
-
JS对象操作对象增删改查创建对象letobj={}新增属性obj.a=1修改属性obj.a='a'...
- 趣谈JS二进制:File、Blob、FileReader、ArrayBuffer、Base64
-
大家好,我是Echa。好久没跟粉丝们细聊JavaScript那点事了。做一名全栈工程师,JS基础还是要打牢,这样的话不管底层业务逻辑以及第三方框架怎么变化,都离不开基础。本文文章属于基础篇,阅读有点...
- 告别 substr() 和 substring()?更可靠的 JavaScript 字符串截取方法
-
JavaScript提供了三个主要的字符串截取方法:...
- golang第九天,切片(slice)介绍(golang 切片作为参数)
-
什么是切片golang切片是对数组的抽象。go的数组长度不可改变,在特定场景中这样的集合就不太适用,go中提供了一种灵活,功能强悍的内置类型切片(“动态数组”),与数组相比切片的长度是不固定的,可以追...
- Go语言零到一:数组(go struct数组)
-
引言...
- 你说你熟悉Slice,这道slice题你能答对吗?
-
每当你花费大量时间使用某种特定工具时,深入了解它并了解如何高效地使用它是很值得的。...
- Python 3.14七大新特性总结:从t-string模板到GIL并发优化
-
Python3.14已进入测试阶段,根据PEP745发布计划,该版本已停止引入新功能,也就是说新特征就应该已经固定下来了。所以本文基于当前最新的beta2版本,深入分析了Python3.14中...
- Python 幕后:Python导入import的工作原理
-
更多互联网精彩资讯、工作效率提升关注【飞鱼在浪屿】(日更新)Python最容易被误解的方面其中之一是import。...
- Python元类实现自动化编程的正确姿势
-
元类是Python中用于创建类的类。通过元类机制,开发者可在运行时动态创建和修改类,为框架开发、设计模式实现和高级架构设计提供核心支持。在Python语言的高级特性中,元类占据着独特而重要的地位。作...
- Python字符串详解与示例(python字符串类型及操作)
-
艾瑞巴蒂字符串的干货来了,字符串是程序中最常见的数据类型之一,用来表示数据文本,下面就来介绍下字符串的特性,操作和方法,和一些示例来吧道友:1.字符串的创建在python中字符串可以永单引号(...
- 恕我直言!你对Python里的import一无所知
-
文章来源:https://mp.weixin.qq.com/s/4WAOU_Lzy651IE-2zZSFfQ原文作者:写代码的明哥...
- Python基础:字符串操作(python字符串的用法)
-
字符串是Python中最常用的数据类型之一,用于表示文本数据。我们将学习如何对字符串进行常见的操作,包括创建、访问、修改和处理字符串。通过掌握这些技巧,您将能够更好地处理和操作文本数据。让我们开始吧!...
- Python 中 字符串处理的高效方法,不允许你还不知道
-
以下是Python中字符串处理的高效方法...
- 一周热门
-
-
C# 13 和 .NET 9 全知道 :13 使用 ASP.NET Core 构建网站 (1)
-
因果推断Matching方式实现代码 因果推断模型
-
git pull命令使用实例 git pull--rebase
-
面试官:git pull是哪两个指令的组合?
-
git 执行pull错误如何撤销 git pull fail
-
git pull 和git fetch 命令分别有什么作用?二者有什么区别?
-
git fetch 和git pull 的异同 git中fetch和pull的区别
-
git pull 之后本地代码被覆盖 解决方案
-
还可以这样玩?Git基本原理及各种骚操作,涨知识了
-
git命令之pull git.pull
-
- 最近发表
-
- 台积电提出SRAM存内计算新方法,能效比可达89TOPS/W
- Golang中如何判断两个slice是否相等?
- JS入门基础知识(js基础知识总结笔记)
- 趣谈JS二进制:File、Blob、FileReader、ArrayBuffer、Base64
- 告别 substr() 和 substring()?更可靠的 JavaScript 字符串截取方法
- golang第九天,切片(slice)介绍(golang 切片作为参数)
- Go语言零到一:数组(go struct数组)
- 你说你熟悉Slice,这道slice题你能答对吗?
- Python 3.14七大新特性总结:从t-string模板到GIL并发优化
- Python 幕后:Python导入import的工作原理
- 标签列表
-
- git pull (33)
- git fetch (35)
- mysql insert (35)
- mysql distinct (37)
- concat_ws (36)
- java continue (36)
- jenkins官网 (37)
- mysql 子查询 (37)
- python元组 (33)
- mybatis 分页 (35)
- vba split (37)
- redis watch (34)
- python list sort (37)
- nvarchar2 (34)
- mysql not null (36)
- hmset (35)
- python telnet (35)
- python readlines() 方法 (36)
- munmap (35)
- docker network create (35)
- redis 集合 (37)
- python sftp (37)
- setpriority (34)
- c语言 switch (34)
- git commit (34)