31.37 Flutter Desktop Window Manager
20230805
The window_manager package for Linux, MacOS, and
Windows, allows various desktop options to be managed for the flutter
app. For example, the default window title is the app name as
specified in the pubspec.yaml
. The default (startup) window size is
specified in the operating system specific files in the linux
(??), windows
(??), and macos
(??) directories.
Technically, to set things up for the windowManager, the so-called
method call handler has to be set up before the binary messenger has
been initialized. Thus when we call setMethodCallHandler() below,
before the WidgetsFlutterBinding has been initialized we need to
ensure the WidgetsFlutterBinding is initialized. We do this in the
sample code below as the content for main.dart
.
To support all platforms we need to check if we are running in a web browser (which could be on any of the platforms) and not undertake any window manager activity if so.
import 'dart:io' show Platform;
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:window_manager/window_manager.dart';
void main() async {
// Identify if Desktop or Mobile app.
bool isDesktop = Platform.isLinux || Platform.isMacOS || Platform.isWindows;
// Tune the window manager before runApp to avoid a lag in the UI. For desktop
// (non-web) versions re-size to mimic mobile (as the main target platform).
if (isDesktop && !kIsWeb) {
WidgetsFlutterBinding.ensureInitialized();
await windowManager.ensureInitialized();
WindowOptions windowOptions = WindowOptions(
alwaysOnTop: true,
// The size is overriden in the first instance by, for example,
// linux/my_application.cc. The size here takes effect when Retarting the
// app.
size: Size(450, 700),
title: 'MyApp - test out some functionality of an app.',
alwaysOnTop: true,
backgroundColor: Colors.transparent,
center: true,
skipTaskbar: false,
titleBarStyle: TitleBarStyle.hidden,
);
windowManager.waitUntilReadyToShow(windowOptions, () async {
await windowManager.show();
await windowManager.focus();
await windowManager.setAlwaysOnTop(false);
});
}
runApp(const MyExperienceApp());
}
I was also finding that the app window on my linux desktop was being
displayed underneath my other windows, which was annoying. So a little
trick in the above is to set alwaysOnTop
and then to turn that off
after getting focus. That seems to achieve what I wanted. Keeping
isAlwaysOnTop
active is not useful as the window is then always on
top of every other window.
Your donation will support ongoing availability and give you access to the PDF version of this book. Desktop Survival Guides include Data Science, GNU/Linux, and MLHub. Books available on Amazon include Data Mining with Rattle and Essentials of Data Science. Popular open source software includes rattle, wajig, and mlhub. Hosted by Togaware, a pioneer of free and open source software since 1984. Copyright © 1995-2022 Graham.Williams@togaware.com Creative Commons Attribution-ShareAlike 4.0