Coder Social home page Coder Social logo

leanflutter / window_manager Goto Github PK

View Code? Open in Web Editor NEW
651.0 14.0 164.0 638 KB

This plugin allows Flutter desktop apps to resizing and repositioning the window.

Home Page: https://pub.dev/packages/window_manager

License: MIT License

Dart 35.69% Swift 10.59% Ruby 0.78% CMake 6.04% C++ 46.12% C 0.77%
flutter macos windows linux flutter-desktop flutter-web window-manager window-resize window-resizer

window_manager's Introduction

window_manager

pub version All Contributors

This plugin allows Flutter desktop apps to resizing and repositioning the window.


English | 简体中文


Platform Support

Linux macOS Windows
✔️ ✔️ ✔️

Quick Start

Installation

Add this to your package's pubspec.yaml file:

dependencies:
  window_manager: ^0.3.8

Or

dependencies:
  window_manager:
    git:
      url: https://github.com/leanflutter/window_manager.git
      ref: main

Usage

import 'package:flutter/material.dart';
import 'package:window_manager/window_manager.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // Must add this line.
  await windowManager.ensureInitialized();

  WindowOptions windowOptions = WindowOptions(
    size: Size(800, 600),
    center: true,
    backgroundColor: Colors.transparent,
    skipTaskbar: false,
    titleBarStyle: TitleBarStyle.hidden,
  );
  windowManager.waitUntilReadyToShow(windowOptions, () async {
    await windowManager.show();
    await windowManager.focus();
  });

  runApp(MyApp());
}

Please see the example app of this plugin for a full example.

Listening events

import 'package:flutter/cupertino.dart';
import 'package:window_manager/window_manager.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with WindowListener {
  @override
  void initState() {
    super.initState();
    windowManager.addListener(this);
  }

  @override
  void dispose() {
    windowManager.removeListener(this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // ...
  }

  @override
  void onWindowEvent(String eventName) {
    print('[WindowManager] onWindowEvent: $eventName');
  }

  @override
  void onWindowClose() {
    // do something
  }

  @override
  void onWindowFocus() {
    // do something
  }

  @override
  void onWindowBlur() {
    // do something
  }

  @override
  void onWindowMaximize() {
    // do something
  }

  @override
  void onWindowUnmaximize() {
    // do something
  }

  @override
  void onWindowMinimize() {
    // do something
  }

  @override
  void onWindowRestore() {
    // do something
  }

  @override
  void onWindowResize() {
    // do something
  }

  @override
  void onWindowMove() {
    // do something
  }

  @override
  void onWindowEnterFullScreen() {
    // do something
  }

  @override
  void onWindowLeaveFullScreen() {
    // do something
  }
}

Quit on close

If you need to use the hide method, you need to disable QuitOnClose.

macOS

Change the file macos/Runner/AppDelegate.swift as follows:

import Cocoa
import FlutterMacOS

@NSApplicationMain
class AppDelegate: FlutterAppDelegate {
  override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
-    return true
+    return false
  }
}

Confirm before closing

import 'package:flutter/cupertino.dart';
import 'package:window_manager/window_manager.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with WindowListener {
  @override
  void initState() {
    super.initState();
    windowManager.addListener(this);
    _init();
  }

  @override
  void dispose() {
    windowManager.removeListener(this);
    super.dispose();
  }

  void _init() async {
    // Add this line to override the default close handler
    await windowManager.setPreventClose(true);
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    // ...
  }

  @override
  void onWindowClose() async {
    bool _isPreventClose = await windowManager.isPreventClose();
    if (_isPreventClose) {
      showDialog(
        context: context,
        builder: (_) {
          return AlertDialog(
            title: Text('Are you sure you want to close this window?'),
            actions: [
              TextButton(
                child: Text('No'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
              TextButton(
                child: Text('Yes'),
                onPressed: () {
                  Navigator.of(context).pop();
                  await windowManager.destroy();
                },
              ),
            ],
          );
        },
      );
    }
  }
}

Hidden at launch

Linux

Change the file linux/my_application.cc as follows:

...

// Implements GApplication::activate.
static void my_application_activate(GApplication* application) {
  
  ...

  gtk_window_set_default_size(window, 1280, 720);
-  gtk_widget_show(GTK_WIDGET(window));
+  gtk_widget_realize(GTK_WIDGET(window));

  g_autoptr(FlDartProject) project = fl_dart_project_new();
  fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments);

  FlView* view = fl_view_new(project);
  gtk_widget_show(GTK_WIDGET(view));
  gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view));

  fl_register_plugins(FL_PLUGIN_REGISTRY(view));

  gtk_widget_grab_focus(GTK_WIDGET(view));
}

...
macOS

Change the file macos/Runner/MainFlutterWindow.swift as follows:

import Cocoa
import FlutterMacOS
+import window_manager

class MainFlutterWindow: NSWindow {
    override func awakeFromNib() {
        let flutterViewController = FlutterViewController.init()
        let windowFrame = self.frame
        self.contentViewController = flutterViewController
        self.setFrame(windowFrame, display: true)

        RegisterGeneratedPlugins(registry: flutterViewController)

        super.awakeFromNib()
    }

+    override public func order(_ place: NSWindow.OrderingMode, relativeTo otherWin: Int) {
+        super.order(place, relativeTo: otherWin)
+        hiddenWindowAtLaunch()
+    }
}
Windows

Change the file windows/runner/win32_window.cpp as follows:

bool Win32Window::CreateAndShow(const std::wstring& title,
                                const Point& origin,
                                const Size& size) {
  ...                              
  HWND window = CreateWindow(
-      window_class, title.c_str(), WS_OVERLAPPEDWINDOW | WS_VISIBLE,
+      window_class, title.c_str(),
+      WS_OVERLAPPEDWINDOW, // do not add WS_VISIBLE since the window will be shown later
      Scale(origin.x, scale_factor), Scale(origin.y, scale_factor),
      Scale(size.width, scale_factor), Scale(size.height, scale_factor),
      nullptr, nullptr, GetModuleHandle(nullptr), this);

Since flutter 3.7 new windows project Change the file windows/runner/flutter_window.cpp as follows:

bool FlutterWindow::OnCreate() {
  ...
  flutter_controller_->engine()->SetNextFrameCallback([&]() {
-   this->Show();
+   "" //delete this->Show()
  });

Make sure to call setState once on the onWindowFocus event.

import 'package:flutter/cupertino.dart';
import 'package:window_manager/window_manager.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with WindowListener {
  @override
  void initState() {
    super.initState();
    windowManager.addListener(this);
  }

  @override
  void dispose() {
    windowManager.removeListener(this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // ...
  }

  @override
  void onWindowFocus() {
    // Make sure to call once.
    setState(() {});
    // do something
  }
}

Articles

Who's using it?

  • Airclap - Send any file to any device. cross platform, ultra fast and easy to use.
  • AuthPass - Password Manager based on Flutter for all platforms. Keepass 2.x (kdbx 3.x) compatible.
  • Biyi (比译) - A convenient translation and dictionary app written in dart / Flutter.
  • BlueBubbles - BlueBubbles is an ecosystem of apps bringing iMessage to Android, Windows, and Linux
  • LunaSea - A self-hosted controller for mobile and macOS built using the Flutter framework.
  • Linwood Butterfly - Open source note taking app written in Flutter
  • RustDesk - Yet another remote desktop software, written in Rust. Works out of the box, no configuration required.
  • Ubuntu Desktop Installer - This project is a modern implementation of the Ubuntu Desktop installer.

API

WindowManager

Methods

waitUntilReadyToShow

Wait until ready to show.

destroy

Force closing the window.

close

Try to close the window.

isPreventClose

Check if is intercepting the native close signal.

setPreventClose

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.

focus

Focuses on the window.

blur macos windows

Removes focus from the window.

isFocused macos windows

Returns bool - Whether window is focused.

show

Shows and gives focus to the window.

hide

Hides the window.

isVisible

Returns bool - Whether the window is visible to the user.

isMaximized

Returns bool - Whether the window is maximized.

maximize

Maximizes the window. vertically simulates aero snap, only works on Windows

unmaximize

Unmaximizes the window.

isMinimized

Returns bool - Whether the window is minimized.

minimize

Minimizes the window. On some platforms the minimized window will be shown in the Dock.

restore

Restores the window from minimized state to its previous state.

isFullScreen

Returns bool - Whether the window is in fullscreen mode.

setFullScreen

Sets whether the window should be in fullscreen mode.

isDockable windows

Returns bool - Whether the window is dockable or not.

isDocked windows

Returns bool - Whether the window is docked.

dock windows

Docks the window. only works on Windows

undock windows

Undocks the window. only works on Windows

setAspectRatio

This will make a window maintain an aspect ratio.

setBackgroundColor

Sets the background color of the window.

setAlignment

Move the window to a position aligned with the screen.

center

Moves window to the center of the screen.

getBounds

Returns Rect - The bounds of the window as Object.

setBounds

Resizes and moves the window to the supplied bounds.

getSize

Returns Size - Contains the window's width and height.

setSize

Resizes the window to width and height.

getPosition

Returns Offset - Contains the window's current position.

setPosition

Moves window to position.

setMinimumSize

Sets the minimum size of window to width and height.

setMaximumSize

Sets the maximum size of window to width and height.

isResizable

Returns bool - Whether the window can be manually resized by the user.

setResizable

Sets whether the window can be manually resized by the user.

isMovable macos

Returns bool - Whether the window can be moved by user.

setMovable macos

Sets whether the window can be moved by user.

isMinimizable macos windows

Returns bool - Whether the window can be manually minimized by the user.

setMinimizable macos windows

Sets whether the window can be manually minimized by user.

isClosable windows

Returns bool - Whether the window can be manually closed by user.

isMaximizable macos windows

Returns bool - Whether the window can be manually maximized by the user.

setMaximizable

Sets whether the window can be manually maximized by the user.

setClosable macos windows

Sets whether the window can be manually closed by user.

isAlwaysOnTop

Returns bool - Whether the window is always on top of other windows.

setAlwaysOnTop

Sets whether the window should show always on top of other windows.

isAlwaysOnBottom

Returns bool - Whether the window is always below other windows.

setAlwaysOnBottom linux windows

Sets whether the window should show always below other windows.

getTitle

Returns String - The title of the native window.

setTitle

Changes the title of native window to title.

setTitleBarStyle

Changes the title bar style of native window.

getTitleBarHeight

Returns int - The title bar height of the native window.

isSkipTaskbar

Returns bool - Whether skipping taskbar is enabled.

setSkipTaskbar

Makes the window not show in the taskbar / dock.

setProgressBar macos windows

Sets progress value in progress bar. Valid range is [0, 1.0].

setIcon windows

Sets window/taskbar icon.

isVisibleOnAllWorkspaces macos

Returns bool - Whether the window is visible on all workspaces.

setVisibleOnAllWorkspaces macos

Sets whether the window should be visible on all workspaces.

Note: If you need to support dragging a window on top of a fullscreen window on another screen, you need to modify MainFlutterWindow to inherit from NSPanel

class MainFlutterWindow: NSPanel {
// ...
}
setBadgeLabel macos

Set/unset label on taskbar(dock) app icon

Note that it's required to request access at your AppDelegate.swift like this: UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge])

hasShadow macos windows

Returns bool - Whether the window has a shadow. On Windows, always returns true unless window is frameless.

setHasShadow macos windows

Sets whether the window should have a shadow. On Windows, doesn't do anything unless window is frameless.

getOpacity

Returns double - between 0.0 (fully transparent) and 1.0 (fully opaque).

setOpacity

Sets the opacity of the window.

setBrightness

Sets the brightness of the window.

setIgnoreMouseEvents

Makes the window ignore all mouse events.

All mouse events happened in this window will be passed to the window below this window, but if this window has focus, it will still receive keyboard events.

startDragging

Starts a window drag based on the specified mouse-down event.

startResizing linux windows

Starts a window resize based on the specified mouse-down & mouse-move event.

grabKeyboard linux

Grabs the keyboard.

ungrabKeyboard linux

Ungrabs the keyboard.

WindowListener

Methods

onWindowClose

Emitted when the window is going to be closed.

onWindowFocus

Emitted when the window gains focus.

onWindowBlur

Emitted when the window loses focus.

onWindowMaximize

Emitted when window is maximized.

onWindowUnmaximize

Emitted when the window exits from a maximized state.

onWindowMinimize

Emitted when the window is minimized.

onWindowRestore

Emitted when the window is restored from a minimized state.

onWindowResize

Emitted after the window has been resized.

onWindowResized macos windows

Emitted once when the window has finished being resized.

onWindowMove

Emitted when the window is being moved to a new position.

onWindowMoved macos windows

Emitted once when the window is moved to a new position.

onWindowEnterFullScreen

Emitted when the window enters a full-screen state.

onWindowLeaveFullScreen

Emitted when the window leaves a full-screen state.

onWindowDocked windows

Emitted when the window entered a docked state.

onWindowUndocked windows

Emitted when the window leaves a docked state.

onWindowEvent

Emitted all events.

Contributors

LiJianying
LiJianying

💻
 A Arif A S
A Arif A S

💻
J-P Nurmi
J-P Nurmi

💻
Dixeran
Dixeran

💻
nikitatg
nikitatg

💻
Kristen McWilliam
Kristen McWilliam

💻
Kingtous
Kingtous

💻
Prome
Prome

💻
Bin
Bin

💻
youxiachai
youxiachai

💻
Allen Xu
Allen Xu

💻
CodeDoctor
CodeDoctor

💻
Jean-Christophe Binet
Jean-Christophe Binet

💻
Jon Salmon
Jon Salmon

💻
Karol Wrótniak
Karol Wrótniak

💻
LAIIIHZ
LAIIIHZ

💻
Mikhail Kulesh
Mikhail Kulesh

💻
Prateek Sunal
Prateek Sunal

💻
Ricardo Boss
Ricardo Boss

💻
Add your contributions

License

MIT

window_manager's People

Contributors

aexei avatar allenxuxu avatar arran4 avatar boyan01 avatar cbenhagen avatar codedoctorde avatar dixeran avatar hlwhl avatar jcbinet avatar jon-salmon avatar jpnurmi avatar juliendev avatar keepgagaga avatar kingtous avatar koral-- avatar laiiihz avatar liangludev avatar lijy91 avatar lunxinfeng avatar merrit avatar mkulesh avatar nikitatg avatar obiwanzenobi avatar prateekmedia avatar raja-s avatar ricardoboss avatar tienisto avatar wisetarman avatar youxiachai avatar zsien avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

window_manager's Issues

macOS 最小化之后再调用WindowManager.instance.show()会导致app崩溃退出

在macOS上,如果先把app最小化之后,再调用WindowManager.instance.show(),会导致app崩溃退出。
以下是一些额外信息:

错误信息

2021-10-09 23:12:57.047 foca_macos_new[88708:621218] *** Assertion failure in -[FlutterViewController listenForMetaModifiedKeyUpEvents], ../../flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController.mm:383
2021-10-09 23:12:57.070 foca_macos_new[88708:621218] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '_keyUpMonitor was already created'

*** First throw call stack:
(
0 CoreFoundation 0x00007ff8122e3c3b __exceptionPreprocess + 242
1 libobjc.A.dylib 0x00007ff81204adce objc_exception_throw + 48
2 Foundation 0x00007ff8130bbd73 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 267
3 FlutterMacOS 0x0000000114ab2f2c -[FlutterViewController listenForMetaModifiedKeyUpEvents] + 380
4 FlutterMacOS 0x0000000114ab2b55 -[FlutterViewController viewWillAppear] + 117
5 AppKit 0x00007ff814ce3d11 -[NSViewController _sendViewWillAppear] + 40
6 AppKit 0x00007ff814ce9c4d -[NSViewController _windowDidOrderOnScreen] + 107
7 AppKit 0x00007ff81541c319 -[NSView _windowDidOrderOnScreen] + 67
8 AppKit 0x00007ff81541c3af -[NSView _windowDidOrderOnScreen] + 217
9 AppKit 0x00007ff814ce1f7d -[NSWindow _reallyDoOrderWindowAboveOrBelow:relativeTo:findKey:forCounter:force:isModal:] + 2034
10 AppKit 0x00007ff814ce1436 -[NSWindow _reallyDoOrderWindow:relativeTo:findKey:forCounter:force:isModal:] + 135
11 AppKit 0x00007ff814ce042b -[NSWindow _doOrderWindow:relativeTo:findKey:forCounter:force:isModal:] + 289
12 AppKit 0x00007ff814ce02a9 -[NSWindow orderWindow:relativeTo:] + 152
13 AppKit 0x00007ff814cd4e90 -[NSWindow makeKeyAndOrderFront:] + 60
14 window_size 0x0000000109d3caf4 -[FLEWindowSizePlugin handleMethodCall:result:] + 8724
15 FlutterMacOS 0x0000000114a9e0ad __56-[FlutterEngineRegistrar addMethodCallDelegate:channel:]_block_invoke + 45
16 FlutterMacOS 0x000000011568ba97 __45-[FlutterMethodChannel setMethodCallHandler:]_block_invoke + 119
17 FlutterMacOS 0x0000000114aa06a1 -[FlutterEngine engineCallbackOnPlatformMessage:] + 289
18 FlutterMacOS 0x0000000114a9eeac _ZL17OnPlatformMessagePK22FlutterPlatformMessageP13FlutterEngine + 44
19 FlutterMacOS 0x00000001152d7fbd _ZNSt3__110__function6__funcIZ23FlutterEngineInitializeE4$49NS_9allocatorIS2_EEFvNS_10unique_ptrIN7flutter15PlatformMessageENS_14default_deleteIS7_EEEEEEclEOSA + 141
20 FlutterMacOS 0x00000001152e920a _ZN7flutter20PlatformViewEmbedder21HandlePlatformMessageENSt3__110unique_ptrINS_15PlatformMessageENS1_14default_deleteIS3_EEEE + 74
21 FlutterMacOS 0x0000000115043b84 _ZNSt3__110__function6__funcIN3fml8internal14CopyableLambdaIZN7flutter5Shell29OnEngineHandlePlatformMessageENS_10unique_ptrINS5_15PlatformMessageENS_14default_deleteIS8_EEEEE4$_16EENS_9allocatorISD_EEFvvEEclEv + 132
22 FlutterMacOS 0x00000001152e6522 _ZN7flutter18EmbedderTaskRunner8PostTaskEy + 738
23 FlutterMacOS 0x00000001152ce57c FlutterEngineRunTask + 44
24 FlutterMacOS 0x0000000114aa1807 __60-[FlutterEngine postMainThreadTask:targetTimeInNanoseconds:]_block_invoke + 71
25 libdispatch.dylib 0x00007ff811fecfe8 _dispatch_call_block_and_release + 12
26 libdispatch.dylib 0x00007ff811fee1d9 _dispatch_client_callout + 8
27 libdispatch.dylib 0x00007ff811ffa863 _dispatch_main_queue_callback_4CF + 949
28 CoreFoundation 0x00007ff8122a6a18 CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE + 9
29 CoreFoundation 0x00007ff812268066 __CFRunLoopRun + 2760
30 CoreFoundation 0x00007ff812266ec9 CFRunLoopRunSpecific + 567
31 HIToolbox 0x00007ff81b3398a1 RunCurrentEventLoopInMode + 292
32 HIToolbox 0x00007ff81b3395f7 ReceiveNextEventCommon + 587
33 HIToolbox 0x00007ff81b339395 _BlockUntilNextEventMatchingListInModeWithFilter + 70
34 AppKit 0x00007ff814ba9290 _DPSNextEvent + 886
35 AppKit 0x00007ff814ba78fc -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 1411
36 AppKit 0x00007ff814b998e5 -[NSApplication run] + 586
37 AppKit 0x00007ff814b6da40 NSApplicationMain + 816
38 foca_macos_new 0x0000000100ab4a1d main + 13
39 dyld 0x0000000200c244d5 start + 421
40 dyld 0x0000000200c1f000 dyld + 0
41 foca_macos_new 0x0000000100aaf000 __dso_handle + 0
)
libc++abi: terminating with uncaught exception of type NSException
Lost connection to device.
Exited (sigterm)

flutter doctor -v

[✓] Flutter (Channel stable, 2.5.0, on macOS 12.0 21A5506j darwin-arm, locale en-SE)
• Flutter version 2.5.0 at /Users/raphael/development/flutter
• Upstream repository https://github.com/flutter/flutter.git
• Framework revision 4cc385b4b8 (5 weeks ago), 2021-09-07 23:01:49 -0700
• Engine revision f0826da7ef
• Dart version 2.14.0

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
• Android SDK at /Users/raphael/Library/Android/sdk
• Platform android-30, build-tools 30.0.3
• Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)
• All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS
• Xcode at /Applications/Xcode.app/Contents/Developer
• Xcode 12.5.1, Build version 12E507
• CocoaPods version 1.10.0

[✓] Chrome - develop for the web
• Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 4.1)
• Android Studio at /Applications/Android Studio.app/Contents
• Flutter plugin can be installed from:
🔨 https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
🔨 https://plugins.jetbrains.com/plugin/6351-dart
• Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)

[✓] VS Code (version 1.61.0-insider)
• VS Code at /Applications/Visual Studio Code - Insiders.app/Contents
• Flutter extension version 3.27.0

[✓] Connected device (2 available)
• macOS (desktop) • macos • darwin-arm64 • macOS 12.0 21A5506j darwin-arm
• Chrome (web) • chrome • web-javascript • Google Chrome 94.0.4606.71

• No issues found!

类似的问题可以参见这里:bitsdojo/bitsdojo_window#82
目测相关的flutter pub package都有类似的问题。

[MacOS] windowManager.hide() kills the flutter app

First - thanks for all the packages that improve flutter desktop experience, they are essential for building apps that integrate with the desktop OSes. Great job.

I've been trying to build a flutter app that can be shown/hidden using a system-wide hotkey using this package and https://github.com/leanflutter/hotkey_manager.

I created a default flutter app with flutter create, enabled MacOS support and added window_manager: ^0.0.5 + hotkey_manager: ^0.1.4 as dependencies.
Next, I changed the main() method to look like this https://pastebin.com/wGNinbzW.

When I hit alt + q the app is shown and I can interact with the UI. After I hit the hotkey again, the app is hidden but I no longer can show it again with the same key combination.
When running in debug mode, the following is returned in the console:

Launching lib/main.dart on macOS in debug mode...
lib/main.dart:1
--- xcodebuild: WARNING: Using the first of multiple matching destinations:
{ platform:macOS, arch:x86_64, id:023A239B-6591-577A-8E58-6FA382A6710C }
{ platform:macOS, name:Any Mac }
Connecting to VM Service at ws://127.0.0.1:50391/GHnaYaoFjW0=/ws
Lost connection to device.
Exited (sigterm)

When the app is launched with flutter run -d macos --release, no errors are shown but I cannot find the app process with ps.

example里跑起来的项目setResizeble不起作用

[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: MissingPluginException(No implementation found for method setResizable on channel window_manager)
#0      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:154:7)
<asynchronous suspension>

[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: MissingPluginException(No implementation found for method isResizable on channel window_manager)
#0      MethodChannel._invokeMethod (package:f

无法调整窗口大小

createSubWindow

看到暴露这个API,请问下怎么使用,目前使用过程中发现直接报错了。
版本:
window_manager: 0.1.2
使用:

         await windowManager
          .createSubWindow(
            title: "设置",
            position: Offset.zero,
            size: const Size(600, 600),
          )
          .catchError(
            (errr) => debugPrint(errr),
          );

错误提示:

window_manager/WindowManager.swift:377: Fatal error: Unexpectedly found nil while unwrapping an Optional value

Hide window title bar

Is it possible to resize a frameless window or to hide the title bar of the window?
I would like to add my own design of the action buttons (minimize, maximize, close).
I've managed to do it on MacOS using Xcode but I struggle to do it on Windows.

Thank you for this amazing lib!

add titleBarHeight

bitsdojo_window库中能获取到titleBarHeight,希望作者能在这个库中也添加上

Add "support" for mobile and web

Hey im using your package in my completely cross-platform project. And right now there's no simple way to compile the same code for mobile / web / desktop. What about adding "support" for mobile devices and do just nothing there?

鼠标移到顶部边界, 不会触发拉伸窗口的箭头, 不能改变窗口大小

鼠标移到顶部边界, 不会触发拉伸窗口的箭头, 不能改变窗口大小, 其他三个方向都正常.
`
[√] Flutter (Channel beta, 2.9.0-0.1.pre, on Microsoft Windows [Version 10.0.19044.1415], locale zh-CN)
• Flutter version 2.9.0-0.1.pre at D:\flutter
• Upstream repository https://github.com/flutter/flutter.git
• Framework revision 8f1f9c10f0 (3 weeks ago), 2021-12-14 13:41:48 -0800
• Engine revision 234aca678a
• Dart version 2.16.0 (build 2.16.0-80.1.beta)
• DevTools version 2.9.1

cupertino_icons: ^1.0.2
win_toast: ^0.0.2
get_storage: ^2.0.3
flutter_window_close: ^0.2.0
window_manager: ^0.1.1
tray_manager: ^0.1.2
file_picker: ^4.3.0
`

ability to know some action ended

Sorry, my English skill is no good...
Currently, we don't know when the user operation ended:
If provide some extra parameters, it would be very helpful:

// when resizing the window, we will receive a bunch of resizing-message, but can't determine the last one(mouse left click up)
void onWindowResize(int state) {
  ....
}
void onWindowMove(int state) {
}

setMinimizable not working on windows 10

[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: MissingPluginException(No implementation found for method setMinimizable on channel window_manager)

Hi i tryed to use setMinimizable(false) but it gives me this error and it's not working I tried to run flutter clean and run the app again but nothing happens.

[Suggestion] [Windows] Use a Flutter widget for top resizing region overlay

If anything else fail, I suggest we make a widget that simulates the original behavior for the top region of the app in titleBarStyle hidden.
When said widget is hovered, change the cursor to SystemMouseCursors.resizeUp or resizeUpLeftDownRight or resizeUpRightDownLeft.
When said widget is clicked, call native event for resizing like in the now discontinued window_utils package, there exist a function startResize(DragPosition position).

Minimizing under windows will trigger view redraw

///  hide title bar
await windowManager.setTitleBarStyle('hidden', windowButtonVisibility: false);

/// or frameless mode
await windowManager.setAsFrameless();

If the window is set to frameless mode or the title bar is set to be hidden, the page will be redrawn when minimized

Some useful functions.

It is a very useful widget and let my app better.
I have some suggestions for it

  1. remove standard Windows/macOS/Linux title bar and buttons
  2. Hide window on startup
  3. consider scaleFactor

I found https://pub.dev/packages/bitsdojo_window support these functions.
But the owner did not update for more than 6 months.

onWindowMinimize, onWindowFocus and onWindowBlur not working in Windows

onWindowMaximize events can be detected properly, but onWindowMinimize, onWindowFocus and onWindowBlur fails.

With the code attached below, I can only see onWindowMaximize in the log.

image

import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:window_manager/window_manager.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await windowManager.ensureInitialized();

  windowManager.waitUntilReadyToShow().then((_) async {
    windowManager.show();
  });

  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with WindowListener {
  int _counter = 0;

  @override
  void initState() {
    windowManager.addListener(this);
    super.initState();
  }

  @override
  void dispose() {
    windowManager.removeListener(this);
    super.dispose();
  }

  @override
  void onWindowMaximize() {
    log('[WindowManager] onWindowMaximize');
  }

  @override
  void onWindowMinimize() {
    log('[WindowManager] onWindowMinimize');
  }

  @override
  void onWindowFocus() {
    log('[WindowManager] onWindowFocus');
  }

  @override
  void onWindowBlur() {
    log('[WindowManager] onWindowBlur');
  }

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

setSize but to the left and top

The current setSize resizes only to the right and bottom direction, so I'm asking if it is possible or is there a plan for a setSize that resizes to the left and/or to the top direction?

setAsFrameless compatibility

in readme not specified setAsFrameless method
can i know which platform supported it ?

another question, for example setClosable not available in windows, if i call it in windows, you handle exception or i must do it ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.