mafulechka
mafulechkaJune 23, 2020, 6:09 a.m.

Flutter and desktop apps

Continuous progress in computer technology

It's no secret that the Flutter developers' mission is to target a wide range of devices including iOS, Android, Windows, Linux, macOS and websites from a single codebase, with native compilation and game-quality rendering. . Google Flutter uses projects from Assistant to Stadia, from Cloud Search to Blogger. Outside of Google, Flutter has been adopted by companies from ByteDance to Grab, Nubank to MGM Resorts, who benefit from Flutter's performance and flexibility.


Many of you are interested in progress in desktop operating systems, including Windows, macOS and Linux. In surveys and on GitHub, the desktop is consistently one of the most popular new features. In the coming weeks, the developers are going to show more of their work, and will start with an overview of some of the work of the various groups that contribute to the overall project. While desktop support is a technical preview, there is still a lot of work ahead.

Release Mode

The developers recently tested the profile and release mode for Windows and Linux, in addition to existing macOS support. For example, if you are using the latest builds of Flutter, you can now compile your Flutter app into a Windows executable with flutter build windows. It uses the AOT production compiler to generate native x64 native code that can be distributed to a machine without Flutter installed.

Desktop

Whether you are creating standalone executables or web applications, you have unique attributes for creating desktop applications. Desktop windows are typically in landscape mode and are resizable, input is typically from the physical keyboard and mouse rather than the on-screen keyboard and touch, and controls are optimized for different screen densities.

At the infrastructure level, developers have made various changes to Flutter to support desktop interaction.

• When creating a new project in recent builds, you will see that the default template now contains a reference to the visualDensity property, which allows controls to adapt their density based on the platform they are targeting, with a more compact range on desktop platforms. An example of how this is used is the TextField, which now offers compact, comfortable, and standard spacing based on the given density.

• Developers have added much better support for mouse and keyboard input - this includes raw Windows keycodes, right-clicking, cursor changes, and scroll wheel support.

• You can now query a specific platform (via the Platform class) and Windows, macOS, and Linux provide the appropriate results.

• In the latest release, the developers have added the NavigationRail widget, which is specially designed for desktops and tablets.

FFI

The Dart team has been hard at work polishing the Foreign Function Interface (FFI), which is a great way to speed up integration with the platform. For APIs based on the dart:ffi library, a direct mechanism for linking to native code is provided. The Dart runtime provides the ability to allocate memory on the heap, which is backed by a Dart object, and make calls to dynamically linked libraries.

For a simple Windows example, here is a code snippet to call the traditional Win32 MessageBox() API in full with Dart code:

typedef MessageBoxNative = Int32 Function(
    IntPtr hWnd, Pointer<Utf16> lpText, Pointer<Utf16> lpCaption, Int32 uType);
typedef MessageBoxDart = int Function(
    int hWnd, Pointer<Utf16> lpText, Pointer<Utf16> lpCaption, int uType);

final user32 = DynamicLibrary.open('user32.dll');
final win32MessageBox =
    user32.lookupFunction<MessageBoxNative, MessageBoxDart>('MessageBoxW');

void showMessageBox(String message, String caption) => win32MessageBox(
    0,                      // No owner window
    Utf16.toUtf16(message), // Message
    Utf16.toUtf16(caption), // Window title
    0                       // OK button only
    );

…

showMessageBox('Test Message', 'Window Caption'); // call just like any other Dart function

Calling the Win32 MessageBox API from Dart code.

In this code, the developers provide a typedef that represents the signature of the method in both its native and Dart representations. Once defined, you can load a Windows Dynamic Link Library (DLL) that provides a function implementation via the lookupFunction() method, which maps a Dart function signature to the underlying native entry point. Finally, we optionally add a simple idiomatic wrapper to make it easily accessible from other Dart code, resulting in something like this:


A simple Windows application example using the Win32 MessageBox API

Of course, you don't have to do this work yourself, chances are someone has already paved the way for the API you want to use.

Updating the plugin model

Flutter itself has a small core. Instead of taking care of the underlying platform, plugins and packages (both directly from the Flutter team and from a wider ecosystem of contributors) provide integration with the underlying operating systems.

However, as Flutter increasingly supports mobile devices, websites, and desktops, developing a plugin for each supported platform becomes more of a challenge. Most likely, the plugin will require contributions from different authors who have experience with each platform.

A useful technique is to define a common interface as part of a core module that each platform can implement independently. Developers have recently adapted the schema for plugins to make it easier to integrate multi-author platform development. As part of this work, it is now possible to explicitly declare which platforms are supported by the plugin.

Developers have also started building some of the main plugins using this model, and you'll find some early examples of the integrated model in the flutter/plugins repository.

Please note that the plugin APIs for Windows and Linux are still in flux, so while the developers encourage exploration, they are not ready for general purpose support at this time. They are also working on adding desktop platform tags to pub.dev.

Works on Windows: Win32 and UWP

One interesting aspect of the work that developers do on Windows is experimenting with different architectural approaches. On any platform, Flutter is embedded in a small host container application (“embedder”), using a similar approach to game engines like Unity. This platform-built injection mechanism provides an entry point, coordinates access to services such as rendering surfaces, accessibility, and input with the underlying operating system, and manages the message event loop.

Windows offers two different approaches for creating this device for embedding. First, the mature Win32 programming model can be used to create an entry point for Flutter content - this ensures maximum backward compatibility with platforms like Windows 7 and creates the standard EXE that many developers expect. Conversely, the modern UWP app model is the recommended approach for Windows 10 and offers intriguing possibilities for extending Flutter support to devices such as the Xbox or the upcoming Windows 10X operating system.

Developers work informally with various contributors to explore various solutions and are happy to work closely with Microsoft to create a high quality solution. They believe that the Surface device family, which includes Android and Windows, offers Microsoft a great platform to build great native apps that span their entire portfolio.

Fun with desktop

This work remains in technical review and the API and tools are not yet stable. Developers still keep track of most of the work they want to do before moving to stable desktop support, including improved accessibility and localization support.

If you want to try this, you need to be in the development channel. Windows and Linux are only available on the master branch, where Flutter is actively developed. macOS is available in the dev branch, which is slightly more stable but not recommended for production use. You can switch channels using flutter channel master or flutter channel dev and then use one of the following commands to enable support for the platform you are using:

C:\flutter> flutter config --enable-windows-desktop$ flutter config --enable-macos-desktop$ flutter config --enable-linux-desktop

Developers have already seen some adventurous developers start using Flutter on the desktop to build apps. One of the first Flutter macOS desktop apps they saw was Sharezone. A student planner targeting the German educational market who started it as a mobile app but recently added web and desktop versions.

Sharezone Schulplan is an app for students, teachers and parents to keep track of homework, study groups and schedules.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
АФ

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:30points,
  • Rating points-10
ПЩ

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
d

C++ - Test 005. Structures and Classes

  • Result:50points,
  • Rating points-4
Last comments
k
kmssrFeb. 8, 2024, 6:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 10:30 a.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 8:38 a.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 18, 2023, 9:01 p.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
AC
Alexandru CodreanuJan. 19, 2024, 11:57 a.m.
QML Обнулить значения SpinBox Доброго времени суток, не могу разобраться с обнулением значение SpinBox находящего в делегате. import QtQuickimport QtQuick.ControlsWindow { width: 640 height: 480 visible: tr…
BlinCT
BlinCTDec. 27, 2023, 8:57 a.m.
Растягивать Image на парент по высоте Ну и само собою дял включения scrollbar надо чтобы был Flickable. Так что выходит как то так Flickable{ id: root anchors.fill: parent clip: true property url linkFile p…
Дмитрий
ДмитрийJan. 10, 2024, 4:18 a.m.
Qt Creator загружает всю оперативную память Проблема решена. Удалось разобраться с помощью утилиты strace. Запустил ее: strace ./qtcreator Начал выводиться весь лог работы креатора. В один момент он начал считывать фай…
Evgenii Legotckoi
Evgenii LegotckoiDec. 12, 2023, 6:48 a.m.
Побуквенное сравнение двух строк Добрый день. Там случайно не высылается этот сигнал textChanged ещё и при форматировани текста? Если решиать в лоб, то можно просто отключать сигнал/слотовое соединение внутри слота и …

Follow us in social networks