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
МВ

Qt - Test 001. Signals and slots

  • Result:68points,
  • Rating points-1
ЛС

C++ - Test 001. The first program and data types

  • Result:53points,
  • Rating points-4
АА

C++ - Test 001. The first program and data types

  • Result:60points,
  • Rating points-1
Last comments
ИМ
Игорь МаксимовOct. 5, 2024, 5:51 p.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 9:02 p.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
k
kmssrFeb. 9, 2024, 5:43 a.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, 9:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
Now discuss on the forum
K
KeithfapOct. 13, 2024, 7:24 p.m.
добавить qlineseries в функции North Symbol by Bubnov Ltd https://seven-elephants.com/en/categories/penthouse/ Искеле – жемчужина острова! Все факторы говорят про большой инвестиционный потенциал данного района как для …
JW
Jhon WickOct. 2, 2024, 1:52 a.m.
Indian Food Restaurant In Columbus OH| Layla’s Kitchen Indian Restaurant If you're looking for a truly authentic https://www.laylaskitchenrestaurantohio.com/ , Layla’s Kitchen Indian Restaurant is your go-to destination. Located at 6152 Cleveland Ave, Colu…
КГ
Кирилл ГусаревSept. 27, 2024, 7:09 p.m.
Не запускается программа на Qt: точка входа в процедуру не найдена в библиотеке DLL Написал программу на C++ Qt в Qt Creator, сбилдил Release с помощью MinGW 64-bit, бинарнику напихал dll-ки с помощью windeployqt.exe. При попытке запуска моей сбилженной программы выдаёт три оши…
F
FynjyJuly 22, 2024, 2:15 p.m.
при создании qml проекта Kits есть но недоступны для выбора Поставил Qt Creator 11.0.2. Qt 6.4.3 При создании проекта Qml не могу выбрать Kits, они все недоступны, хотя настроены и при создании обычного Qt Widget приложения их можно выбрать. В чем может …

Follow us in social networks