window_manager_plus 是一个专为 macOS、Windows 和 Linux 上的桌面应用程序设计的 Flutter 插件。它使开发者能够创建、管理和操作多个窗口,支持调整大小、重新定位以及窗口间通信等功能。该包简化了复杂的窗口处理任务,让构建具有动态 UI 布局的丰富桌面体验变得更加容易。它可无缝集成到现有的 Flutter 项目中,并提供一致的 API 支持跨平台窗口管理。
适合场景
构建多窗口桌面应用程序
创建可调整大小且可移动的窗口
实现窗口间消息传递
开发仪表板或编辑器界面
管理浮动面板或工具窗口
主要特点
支持多个窗口
调整窗口大小和重新定位窗口
跨窗口通信
跨平台兼容性
简单的 API 集成
适合对象
桌面应用程序开发者
多窗口应用程序创建者
面向桌面的 Flutter 开发人员
需要灵活布局的UI设计师
需要模块化窗口组件的应用程序
使用建议
需要 Flutter 3.0+
仅限桌面平台
可能需要平台特定的配置
不适合用于移动应用
依赖于底层操作系统窗口系统
原始 README
以下为关联源码仓库的 README 原文快照,最新内容请访问源码仓库。
window_manager_plus
This plugin allows Flutter desktop apps to create and manage multiple windows, such as resizing and repositioning, and communicate between them.
This is a fork and a re-work of the original window_manager plugin.
With inspiration from the desktop_multi_window plugin,
this new implementation allows the creation and management of multiple windows.
Change the file macos/Runner/AppDelegate.swift as follows:
import Cocoa
import FlutterMacOS
+ import window_manager_plus
@main
class AppDelegate: FlutterAppDelegate {
override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
- return true+ return NSApp.windows.filter({$0 is MainFlutterWindow || $0 is WindowManagerPlusFlutterWindow}).count == 1 // or return false
}
}
Without changing the return logic, the application will close when the main flutter window is closed.
Windows
Change the file windows/runner/main.cpp as follows:
#include <flutter/dart_project.h>
#include <flutter/flutter_view_controller.h>
#include <windows.h>
#include "flutter_window.h"
#include "utils.h"
+ #include <iostream>+ #include "window_manager_plus/window_manager_plus_plugin.h"
int APIENTRY wWinMain(_In_ HINSTANCE instance,
_In_opt_ HINSTANCE prev,
_In_ wchar_t* command_line,
_In_ int show_command) {
// Attach to console when present (e.g., 'flutter run') or create a
// new console when running with a debugger.
if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
CreateAndAttachConsole();
}
// Initialize COM, so that it is available for use in the library and/or
// plugins.
::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
flutter::DartProject project(L"data");
std::vector<std::string> command_line_arguments = GetCommandLineArguments();
project.set_dart_entrypoint_arguments(std::move(command_line_arguments));
FlutterWindow window(project);
Win32Window::Point origin(10, 10);
Win32Window::Size size(1280, 720);
if (!window.Create(L"window_manager_example", origin, size)) {
return EXIT_FAILURE;
}
- window.SetQuitOnClose(true);+ window.SetQuitOnClose(false);++ WindowManagerPlusPluginSetWindowCreatedCallback(+ [](std::vector<std::string> command_line_arguments) {+ flutter::DartProject project(L"data");++ project.set_dart_entrypoint_arguments(+ std::move(command_line_arguments));++ auto window = std::make_shared<FlutterWindow>(project);+ Win32Window::Point origin(10, 10);+ Win32Window::Size size(1280, 720);+ // Check whether window->Create or window->CreateAndShow is available.+ // Take a look at the code above for the main flutter window and + // what method the variable "FlutterWindow window(project)" calls+ if (!window->Create(L"window_manager_example", origin, size)) {+ std::cerr << "Failed to create a new window" << std::endl;+ }+ window->SetQuitOnClose(false);+ return std::move(window);+ });
::MSG msg;
while (::GetMessage(&msg, nullptr, 0, 0)) {
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
::CoUninitialize();
return EXIT_SUCCESS;
}
window->SetQuitOnClose(false); is necessary to prevent the application from closing when the window is closed.
If you want to close the App only when the main window is closed, you can set window->SetQuitOnClose(true); in the main window.
The others called inside the WindowManagerPlusPluginSetWindowCreatedCallback should be set to false.
Usage
You must call WindowManagerPlus.ensureInitialized static method and await it before using any WindowManagerPlus methods or WindowManagerPlus.current.
It is used to initialize the plugin with the current window ID.
When creating a new window, the args parameter of the main function will have the window ID as a String.
You must parse it to an integer and pass it to the WindowManagerPlus.ensureInitialized method.
If the args parameter is empty or the first argument is not an integer, then we are in the main window, which ID is exactly 0.
The other arguments will contain the arguments passed to the WindowManagerPlus.createWindow method, if any.
import'package:flutter/material.dart';
import'package:window_manager_plus/window_manager_plus.dart';
// Must add List<String> args parameter to your main function.voidmain(List<String> args) async {
WidgetsFlutterBinding.ensureInitialized();
// await the initialization of the plugin.// Here is an example of how to use ensureInitialized in the main function:awaitWindowManagerPlus.ensureInitialized(args.isEmpty ? 0 : int.tryParse(args[0]) ?? 0);
// Now you can use the plugin, such as WindowManagerPlus.currentWindowOptions windowOptions = WindowOptions(
size: Size(800, 600),
center: true,
backgroundColor: Colors.transparent,
skipTaskbar: false,
titleBarStyle: TitleBarStyle.hidden,
);
WindowManagerPlus.current.waitUntilReadyToShow(windowOptions, () async {
awaitWindowManagerPlus.current.show();
awaitWindowManagerPlus.current.focus();
});
runApp(MyApp());
}
Create a new window
You can create a new window by calling the WindowManagerPlus.createWindow static method.
If you want control the new window, you can use the return value of the method, which returns a WindowManagerPlus instance.
final newWindow = awaitWindowManagerPlus.createWindow(['my test arg 1', 'my test arg 2']);
if (newWindow != null) {
print('New Created Window: $newWindow');
}
Communication between windows
You can communicate with another window by using the WindowManagerPlus.invokeMethodToWindow method.
The first parameter is the ID of the window you want to communicate with.
The second parameter is the method name you want to call.
The third parameter is the arguments you want to pass to the method, if any.
The other window must register and implement the WindowListener class and override the WindowListener.onEventFromWindow method to receive the event.
// assuming we are in the first window, Window ID 0, and we want to communicate with the second window.final secondWindowId = 1; // ID of the second windowfinal result = awaitWindowManagerPlus.current.invokeMethodToWindow(secondWindowId, 'myTestMethod', ['arg1', 'arg2']);
// the result will be 'Hello from Window 1'// assuming we are in the second window, Window ID 1class_MyWidgetStateextendsState<MyWidget> withWindowListener{
// ...@overridevoidinitState() {
WindowManagerPlus.current.addListener(this);
super.initState();
}
@overridevoiddispose() {
WindowManagerPlus.current.removeListener(this);
super.dispose();
}
// ...@overrideFuture<dynamic> onEventFromWindow(String eventName, int fromWindowId, dynamic arguments) async {
print('[${WindowManagerPlus.current}] Event $eventName from Window $fromWindowId with arguments $arguments');
return'Hello from ${WindowManagerPlus.current}';
}
}
Using WindowManagerPlus.getAllWindowManagerIds() static method you can get all the window manager ids available.
Please see the example app of this plugin for a full example.
Listening events
The WindowListener mixin class is used to listen to window events.
If this is used as a Global Listener using the WindowManagerPlus.addGlobalListener static method,
the windowId parameter will be the ID of the window that emitted the event,
otherwise, it will be always null.
Invokes a method on the window with id targetWindowId. It could return a Future that resolves to the return value of the invoked method, otherwise null. Use WindowListener.onEventFromWindow to listen for the event.
You can call this to remove the window frame (title bar, outline border, etc), which is basically everything except the Flutter view, also can call setTitleBarStyle(TitleBarStyle.normal) or setTitleBarStyle(TitleBarStyle.hidden) to restore it.
Set if intercept the native close signal. May useful when combine with the onclose event listener. This will also prevent the manually triggered close event.