Flutter桌面应用实现只启动一次(单实例)

xiaohai 2022-05-03 11:02:10 5323人围观 标签: Flutter 
简介很多时候我们只希望我们的应用只能启动一次,本文主要介绍下Flutter的windows桌面端如何实现只启动一次的方法。

最先看网上说只启动一次需要修改C++代码,参考文档如下:
Run only single instance of flutter desktop application

代码内容如下:

  1. HANDLE hMutexHandle=CreateMutex(NULL, TRUE, L"my.mutex.name");
  2. HWND handle=FindWindowA(NULL, "Test Application");
  3. if (GetLastError() == ERROR_ALREADY_EXISTS)
  4. {
  5. WINDOWPLACEMENT place = { sizeof(WINDOWPLACEMENT) };
  6. GetWindowPlacement(handle, &place);
  7. switch(place.showCmd)
  8. {
  9. case SW_SHOWMAXIMIZED:
  10. ShowWindow(handle, SW_SHOWMAXIMIZED);
  11. break;
  12. case SW_SHOWMINIMIZED:
  13. ShowWindow(handle, SW_RESTORE);
  14. break;
  15. default:
  16. ShowWindow(handle, SW_NORMAL);
  17. break;
  18. }
  19. SetWindowPos(0, HWND_TOP, 0, 0, 0, 0, SWP_SHOWWINDOW | SWP_NOSIZE | SWP_NOMOVE);
  20. SetForegroundWindow(handle);
  21. return 0;
  22. }

操作那么多实在看不懂,毕竟没有写过C++。通过继续努力寻找,终于在现有的插件中,有这样一款插件可以实现。

windows_single_instance

  1. Add WidgetsFlutterBinding.ensureInitialized(); to the start of your apps main function.
  2. Add the async modifier to your apps main function.
  3. Add a call to WindowsSingleInstance.ensureSingleInstance(), passing the apps startup args, a custom app string unique to your app (a-z, 0-9, _ and - only), and an optional callback function.

使用非常简单

  1. void main(List<String> args) async {
  2. WidgetsFlutterBinding.ensureInitialized();
  3. //单实例启动
  4. await WindowsSingleInstance.ensureSingleInstance(args, "app_id",
  5. onSecondWindow: (args) async {
  6. if (await windowManager.isMinimized()) {
  7. windowManager.restore();
  8. }
  9. windowManager.focus();
  10. });
  11. runApp(const MyApp());
  12. }

以上就可以实现单实例启动了。