31.18 Flutter Desktop App Window Manager

20230805

The window_manager package 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 window size is specified in the operating system specific files in the linux, windows, and macos directories.

To get a little technical, 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 which will be the content for main.dart.

import 'dart:io' show Platform;

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.

  if (isDesktop) {

    WidgetsFlutterBinding.ensureInitialized();

    await windowManager.ensureInitialized();

    WindowOptions windowOptions = WindowOptions(
      alwaysOnTop: true,
      size: Size(450, 700),
      title: APP_TITLE,
      center: true,
      backgroundColor: Colors.transparent,
      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