flutter桌面软件开发|Flutter+Getx仿微信客户端聊天exe

1,255 阅读7分钟

继上一篇flutter3开发手机端App聊天项目获得了很多开发者的点赞支持,时隔一个月又带来了最新完结项目——flutter3桌面端仿微信EXE聊天应用FLUTTER3-WINCHAT

juejin.cn/post/733235…

035360截图20240229224936683.png

这个项目前前后后花了差不多半个多月时间,涉及的知识技术点还是蛮全面的。旨在通过这个项目探索Flutter3在客户端的实践可行性。希望有更多的开发者能推动flutter在桌面端的发展。

036360截图20240229225602857.png

技术栈

  • 编码器:VScode
  • 框架技术:Flutter3+Dart3
  • 窗口管理: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

p3.gif

接着往下看,大家会看到这个项目的一些预览全貌及一些实现技术知识点。

p6.gif

项目结构目录

360截图20240229212947849.png

// 创建flutter新项目模板
flutter create flutter_winchat

// 运行到window桌面
flutter run -d windows

p7.gif

整个项目窗口管理经过考虑最后选择了bitsdojo_window插件,不过window_manager这个窗口管理插件也不错,不过相对重量级一些,功能性更加比较全面。

pub-web.flutter-io.cn/packages/bi…

pub-web.flutter-io.cn/packages/bi…

该项目还使用了flutter桌面端系统托盘 system_tray 插件,生成任务栏托盘图标。

p9.gif

pub-web.flutter-io.cn/packages/sy…

001360截图20240229214508782.png

003360截图20240229215932360.png

006360截图20240229220414749.png

010360截图20240229220828108.png

014360截图20240229222806627.png

017360截图20240229223003763.png

018360截图20240229223136928.png

020360截图20240229223635683.png

021360截图20240229223659252.png

024360截图20240229223836674.png

027360截图20240229224103898.png

031360截图20240229224426889.png

033360截图20240229224606994.png

034360截图20240229224852818.png

038360截图20240229230133112.png

039360截图20240229230209768.png

041360截图20240229230332240.png

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();
    }
  });
}

flutter3路由配置

3119bb4493032cd4697efa6741da6f38_1289798-20240302000031435-522835117.png

使用getx来进行路由/状态管理。

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

flutter客户端自定义最大化/最小化/关闭按钮

image.png

ee30930ef1b75d14af2e4048f7b45823_1289798-20240301233052974-1080211488.png

整个项目使用bitsdojo_window插件进行窗口管理。该插件会去掉系统导航条,自定义窗口大小、右上角操作按钮、拖拽窗口等功能。

4e4e25f33957746b4f3312f997eb5beb_1289798-20240301232120531-1462292712.png

// 最小化
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),)
          ),
        ],
      );
    }
  );
}

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

不过有个问题,通过bitsdojo_window设置最大化/恢复不能实时监测窗口尺寸变化,如何才能实时监听窗口尺寸的更改呢?

可以通过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;
      });
    });
  }

  // ...
}

flutter3布局模板

703a2ac494a1817f071b8a6bda675768_1289798-20240301234053314-1599577350.png

如上图:项目整体参照微信客户端界面。

新建一个公共模板,用于进行Tab切换操作。

7cca5918cf195428071d75a30a536cbe_1289798-20240301234329243-1669585318.png

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();
}

通过MoveWindow组件可实现窗口拖拽功能。

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

cda0d6030b6f2e2bd31eeb926c6c40ad_1289798-20240301234921210-465579708.png

通过 NavigationRail 导航组件实现Tab功能。该组件还支持自定义头部和尾部组件。

@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视频播放模块

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

5aaeb40e3ae2b21324f11769a49b4d6c_1289798-20240302001437075-1135936738.png

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

Container(
  width: MediaQuery.of(context).size.height * 9 / 16,
  decoration: const BoxDecoration(
    color: Colors.black,
  ),
  child: Stack(
    children: [
      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),
          ),
        ),
      ),
    ],
  ),
),

flutter3聊天实现模块

037360截图20240229225918001.png

038360截图20240229230133112.png

表情/选择弹窗均是使用showDialog实现功能。

// 表情弹窗
void showEmojDialog() {
  updateAnchorOffset(anchorEmojKey);
  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 Stack(
            children: [
              Positioned(
                top: anchorDy - (anchorDy - 100) - 15,
                left: anchorDx - 180,
                width: 360.0,
                height: anchorDy - 100,
                child: Material(
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12.0)),
                  color: Colors.white,
                  elevation: 1.0,
                  clipBehavior: Clip.hardEdge,
                  child: Column(
                    children: renderEmojWidget(),
                  ),
                ),
              )
            ],
          );
        },
      );
    },
  );
}

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

showDialog本质上是是一个新路由页面。所以,你使用当前页面的 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(
          ...
        );
      },
    );
  },
);

这样页面上使用setEmojState就能实现和setState一样的功能。

f099cc8f892a14a032f60b5a06c714d0_1289798-20240302010116070-1471429719.png

042360截图20240229230352745.png

按住说话这个模块,在之前的flutter手机端聊天项目中有介绍过,这里就不详细分享了。

juejin.cn/post/731918…

n.sohucs.gif