Flutter桌面应用实现只启动一次(单实例)
简介很多时候我们只希望我们的应用只能启动一次,本文主要介绍下Flutter的windows桌面端如何实现只启动一次的方法。
最先看网上说只启动一次需要修改C++代码,参考文档如下:
Run only single instance of flutter desktop application
代码内容如下:
HANDLE hMutexHandle=CreateMutex(NULL, TRUE, L"my.mutex.name");
HWND handle=FindWindowA(NULL, "Test Application");
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
WINDOWPLACEMENT place = { sizeof(WINDOWPLACEMENT) };
GetWindowPlacement(handle, &place);
switch(place.showCmd)
{
case SW_SHOWMAXIMIZED:
ShowWindow(handle, SW_SHOWMAXIMIZED);
break;
case SW_SHOWMINIMIZED:
ShowWindow(handle, SW_RESTORE);
break;
default:
ShowWindow(handle, SW_NORMAL);
break;
}
SetWindowPos(0, HWND_TOP, 0, 0, 0, 0, SWP_SHOWWINDOW | SWP_NOSIZE | SWP_NOMOVE);
SetForegroundWindow(handle);
return 0;
}
操作那么多实在看不懂,毕竟没有写过C++。通过继续努力寻找,终于在现有的插件中,有这样一款插件可以实现。
Add WidgetsFlutterBinding.ensureInitialized(); to the start of your apps main function.
Add the async modifier to your apps main function.
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.
使用非常简单
void main(List<String> args) async {
WidgetsFlutterBinding.ensureInitialized();
//单实例启动
await WindowsSingleInstance.ensureSingleInstance(args, "app_id",
onSecondWindow: (args) async {
if (await windowManager.isMinimized()) {
windowManager.restore();
}
windowManager.focus();
});
runApp(const MyApp());
}
以上就可以实现单实例启动了。