基于flutter3+getx+bitsdojo_window仿微信客户端|flutter聊天EXE

flutter3_winchat:基于flutter3+dart3+getx+bitsdojo_window等技术开发跨平台仿微信聊天实例。

技术栈

  • 编辑器: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

前前后后开发了大约半个多月,期间也遇到了不少问题。想着该项目涉及到很多知识点,就来做一些分享。

项目结构

整个项目窗口管理采用的bitsdojo_window插件,不过window_manager这个窗口管理插件也不错,不过相对重量级一些。

pub-web.flutter-io.cn/packages/bit...
pub-web.flutter-io.cn/packages/win...

通过flutter create app_proj创建一个新项目。
使用flutter run -d windows来运行到window桌面。

通过 system_tray 插件管理flutter桌面端任务栏托盘图标。
图片
pub-web.flutter-io.cn/packages/sys...

flutter3路由状态配置

采用 getx 作为路由和状态管理。将 MaterialApp 替换为GetMaterialApp 组件。

基于flutter3+getx+bitsdojo_window仿微信客户端|flutter聊天EXE

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,
      ),
      home: const Layout(),
      // 初始路由
      initialRoute: Utils.isLogin() ? '/index' :'/login',
      // 路由页面
      getPages: routes,
    );
  }
}
import 'package:flutter/material.dart';
import 'package:get/get.dart';

// 引入工具类
import '../utils/index.dart';

/* 引入路由页面 */
import '../views/auth/login.dart';
import '../views/auth/register.dart';
// 首页
import '../views/index/index.dart';
// 通讯录
import '../views/contact/index.dart';
import '../views/contact/addfriends.dart';
import '../views/contact/newfriends.dart';
import '../views/contact/uinfo.dart';
// 收藏
import '../views/favor/index.dart';
// 我的
import '../views/my/index.dart';
import '../views/my/setting.dart';
import '../views/my/recharge.dart';
import '../views/my/wallet.dart';
// 朋友圈
import '../views/fzone/index.dart';
import '../views/fzone/publish.dart';
// 短视频
import '../views/fvideo/index.dart';
// 聊天
import '../views/chat/group-chat/chat.dart';

// 路由地址集合
final Map<String, Widget> routeMap = {
  '/index': const Index(),
  '/contact': const Contact(),
  '/addfriends': const AddFriends(),
  '/newfriends': const NewFriends(),
  '/uinfo': const Uinfo(),
  '/favor': const Favor(),
  '/my': const My(),
  '/setting': const Setting(),
  '/recharge': const Recharge(),
  '/wallet': const Wallet(),
  '/fzone': const Fzone(),
  '/publish': const PublishFzone(),
  '/fvideo': const Fvideo(),
  '/chat': const Chat(),
};

final List<GetPage> patchRoute = routeMap.entries.map((e) => GetPage(
  name: e.key, // 路由名称
  page: () => e.value, // 路由页面
  transition: Transition.noTransition, // 跳转路由动画
  middlewares: [AuthMiddleware()], // 路由中间件
)).toList();

final List<GetPage> routes = [
  GetPage(name: '/login', page: () => const Login()),
  GetPage(name: '/register', page: () => const Register()),
  ...patchRoute,
];

通过getx内置的middlewares中间件进行路由跳转拦截。

// 路由拦截
class AuthMiddleware extends GetMiddleware {
  @override
  RouteSettings? redirect(String? route) {
    return Utils.isLogin() ? null : const RouteSettings(name: '/login');
  }
}

flutter桌面端自定义最大化/最小化/关闭

基于flutter3+getx+bitsdojo_window仿微信客户端|flutter聊天EXE

基于flutter3+getx+bitsdojo_window仿微信客户端|flutter聊天EXE

@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布局模板

基于flutter3+getx+bitsdojo_window仿微信客户端|flutter聊天EXE

整个项目参照了桌面端UI界面。

基于flutter3+getx+bitsdojo_window仿微信客户端|flutter聊天EXE

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,
              ),
            ),
          ],
        ),
      ),
    ],
  ),
);

基于flutter3+getx+bitsdojo_window仿微信客户端|flutter聊天EXE

采用 NavigationRail 组件实现侧边导航功能。该组件支持自定义头部和尾部组件。

@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']);
          }
        });
      },
    ),
  );
}

flutter小视频模板

项目中加入了短视频功能。支持上下滑动,点击播放/暂停视频。

// flutter3视频播放模块  Q:282310962

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),
          ),
        ),
      ),
    ],
  ),
),

通过 setState 方法无法更新当前的dialog状态

showDialog本质上是另一个路由页面,它的性质跟你当前主页面是一样的。在Flutter中它是一个新的路由。所以,你使用当前页面的 setState 方法当然是没法更新dialog中内容。如何更新dialog中的内容呢?当然是使用StatefulBuilder组件。

late StateSetter setEmojState;

showDialog(
  context: context,
  barrierColor: Colors.transparent,
  builder: (context) {
    // 解决flutter通过 setState 方法无法更新当前的dialog状态
    // dialog是一个路由页面,本质跟你当前主页面是一样的。在Flutter中它是一个新的路由。所以,你使用当前页面的 setState 方法当然是没法更新dialog中内容。
    // 如何更新dialog中的内容呢?答案是使用StatefulBuilder。
    return StatefulBuilder(
      builder: (BuildContext context, StateSetter setState) {
        setEmojState = setState;
        return Container(
          ...
        );
      },
    );
  },
);

整个项目涵盖的flutter知识点还蛮多的,限于篇幅,今天就分享到这里。
希望以上的分享能给小伙伴们有些帮助!

博客:flutter3-wchat:基于flutter3.x/dart3+material-ui聊天|flutter3仿...
博客:uniapp-welive:基于uni-app+vue3+pinia多端直播商城实例|uniapp仿抖...

本作品采用《CC 协议》,转载必须注明作者和本文链接
本文为原创文章,未经作者允许不得转载,欢迎大家一起交流 QQ(282310962) wx(xy190310)
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
文章
47
粉丝
45
喜欢
101
收藏
54
排名:367
访问:2.6 万
私信
所有博文
博客标签
react
1
angular
1
react仿微信
2
react实战开发
2
react+redux
1
react网页聊天
2
angular仿微信
1
angular聊天室
1
angular+node聊天
1
h5仿微信
1
仿微信语音
1
仿微信界面
1
RN弹窗
1
react-native自定义弹窗
1
react-native弹窗
1
React Native
1
reactNative仿微信
1
RN仿微信聊天
1
ReactNative朋友圈
1
uniapp仿微信
1
uniapp聊天室
2
uniapp聊天App
1
uni-app+vue实例
1
uni-app即时通讯
1
uniapp直播
1
uni-app仿抖音
1
uniapp仿陌陌
1
uni-app小视频
1
taro仿微信
1
taro聊天室
1
taro仿微信界面
1
taro+react聊天APP
1
taro即时通讯
1
electron+vue
1
electron-vue仿微信
1
electron聊天
1
electron实例
1
flutter实例
1
flutter仿微信
1
flutter+dart聊天
1
flutter聊天室
1
flutter聊天界面
1
vue自定义弹窗
1
vue全局对话框
1
vue长按弹出框
1
vue右键弹层
1
nuxt对话框
1
vue仿微信弹窗
1
vue仿探探
1
vue仿Tinder
1
vue卡片堆叠
1
vue翻牌滑动
1
nuxt仿探探
1
nuxt聊天室
1
nuxt仿微信
1
nuxt即时聊天
1
vue+nuxt聊天实例
1
nuxt.js朋友圈
1
vue.js自定义对话框
1
vue pc端弹窗
1
vue.js桌面端模态框
1
vue弹窗组件
1
vue仿layer
1
vue.js自定义滚动条
1
vue虚拟滚动条
1
vue美化滚动条
1
vue仿饿了么滚动条
1
Vue-Scrollbar
1
react.js弹窗示例
1
react桌面端弹框
1
react.js自定义对话框
1
react pc自定义弹窗
1
react全局弹框
1
vue3.0自定义组件
1
vue3弹框
1
vue3.x对话框
1
vue3.0弹窗
1
vue3.0实例
1
vue3.0聊天室
1
vue3.0仿微信
2
vue3聊天模板
1
vue3+vant3实战开发
1
vue3.x案例
1
vue3聊天实例
1
vue3.0仿QQ
1
vue3.x实战聊天
1
vue3网页聊天
1
vue3.0仿抖音app
1
vue3短视频
1
vue3.x小视频
1
vue3.0直播实例
1
vue3+vite2+vant3实战
1
vue3跨端开发
1
electron仿QQ
1
electron打包
1
electron聊天室
1
electron仿微信
1
electron仿抖音
1
electron短视频
1
electron直播
1
vite2+electron12
1
vite2+vue3.x+swiper
1
vue3+vite.js+vant3
1
vue3后台系统
1
Electron管理系统
1
vite2+electron后台
1
electron12权限管理
1
electron桌面端后台
1
vue3桌面管理
1
vite2+electron13
1
electron仿mac桌面
1
electron桌面管理
1
vite2桌面应用
1
uniapp短视频
1
uniapp仿抖音
1
uni-app直播
1
uniapp后台
1
uni-app+uview后台系统
1
svelte.js实战开发
1
svelte3仿微信
1
svelte+svelteKit聊天室
1
svelte聊天实例
2
svelte朋友圈
1
svelte.js仿微信
1
svelte.js网页聊天
1
svelte-ui-admin
1
svelte-admin后台管理
1
svelte管理系统
1
tauri桌面应用
1
tauri+vue3
1
vite3+tauri
1
tauri聊天程序
1
tauri仿微信
1
vue3后台管理
1
vite.js管理系统
1
vue3+vite4
1
vite4+pinia
1
vue3+pinia2
1
vue3-chatgpt
2
vite-chatgpt
1
chatgpt-mobile
1
electron-chatgpt
1
electron+vite4+vue3
1
electron25-vue3
1
chatgpt-vite
1
uni-chatgpt
1
uniapp+vue3+pinia
2
vite+uniapp
1
chatgpt-uniapp
1
tauri-admin
1
tauri+rust+vue3
1
tauri后台管理
1
tauri-vite
1
tauri+vue3桌面端后台
1
react18 hooks
2
react18+arco
2
react18+zustand
1
react18-webchat
1
react18-admin
1
react-arco-admin
1
react-vite-admin
1
react18后台管理
1
electron-mateos
1
electron27+react18
1
electron-react-macos
1
electron桌面os
1
react-macos
1
uniapp+vue3直播
1
flutter3-chat
2
flutter3仿微信
2
flutter3聊天
2
flutter3+dart3
1
flutter3桌面端开发
1
flutter3-douyin
1
flutter3仿抖音
1
flutter3短视频
1
flutter3直播
1
flutter3-macos
1
flutter3-osx
1
flutter3桌面os
1
flutter3仿macOS
1
社区赞助商