Skip to content
All stories

Synchronizing UI across Flutter Engines: Part 1

A dual-screen POS runs two Flutter engines that share no state. We explain the problem and build a step-by-step example app that keeps two windows in sync.

Written by
Suphon ThanakornpakapongNut Pinyo
Published
Filed under
Engineer
Reading time
12 min
Softnetics Journal cover: Synchronizing UI across Flutter Engines: Part 1

Synchronizing UI across Flutter Engines:
Part 1

Hii~ 👋🏻, we are Suphon and Nut, Lead Software Engineers at Softnetics. We are transforming the single most important piece of software in a retail business: the POS System.

A supermarket checkout counter with two screens: the cashier's touchscreen above a POS keyboard, and a customer-facing screen beside it showing the store logo. A card payment terminal stands at the front of the counter.
The POS (Point-of-Sale) System. All sales in store must go through a POS.

This series highlights one of the biggest technical challenges we faced while designing and building the POS:

Keeping the cashier display and the customer display in sync.

On Flutter desktop, this was harder than it sounds: the two Flutter windows could not simply share the same state.

In this part, we will:

  • Explain why we need to keep the windows in sync with messages.
  • Build a small example app step by step, from a single counter to two windows that share a cart.
  • And end with the alternatives we considered.

Why Speed Matters

A checkout always has two people at the counter, but with a single screen, only one of them uses the system. The cashier scans items, asks the customer for their member information, types it in, and fixes any mistakes.

Illustration of a shop checkout. Behind the counter, the cashier asks “What's your member number?” and types it in. In front of it, the customer reads “081-234-5678” from their phone. A second screen faces the customer but only shows a member lookup, so the number is still said out loud.
Cashier types member id, one-by-one, as customer says it.

One of the ways to reduce time per checkout is to have the customer input their member id while cashier scans items. We believe reducing time spent per transaction will improve customer satisfaction and retention.

Our Approach: One Flutter Engine per Window

In native app frameworks, like WinUI on Windows, AppKit on macOS, and GTK on Linux, one app process can open many windows, and every window reads the same objects in memory.

Flutter desktop did not work that way when we built this system: official multi-window support was not yet available, so our implementation gives each window its own Flutter engine: engine A for the cashier window and engine B for the customer window. Each engine runs its own Dart isolate, and isolates do not share memory. A widget, a variable, or a state object in one window does not exist in the other window.

If the cashier adds an item to the cart, engine A knows about it. Engine B does not. To show the same cart on the customer screen, engine A must send that change to engine B, and engine B must apply it.

How a Message Reaches the Other Engine

Flutter already has a useful messaging primitive: BasicMessageChannel. It normally carries messages between Dart and the native code of the app. It does not connect two Flutter engines by itself.

The native side of the app owns both windows, so it can see both engines. It listens on the FlutterToBridge channel in one engine and forwards each message to the BridgeToFlutter channel in the other:

The bridge forwards each message without reading it. The receiving engine can send back a reply, and the bridge returns that reply to the sender. In the example app below, we build this bridge in Step 3.

Building the Example App

The rest of this post builds a small macOS app with two windows and two engines, one step at a time.

Step 1: A Counter App

We start with the default counter app generated by flutter create. The main() function runs an app with a counter widget that displays the current count. A + button increments the counter.

flutter_multi_window_app
The counter app with the counter at 0 and a plus button.

The app currently has one window backed by one Flutter engine. Next, we will open a second window with its own engine and run the same counter app in both.

Step 2: A Second Window

To make changes outside Flutter, we can modify the runner app. The runner is a platform-native application that uses Flutter APIs to embed a Flutter engine into a native window.

In this example, we're using macOS, so we can call AppKit to create another native window like a regular macOS app, and then use Flutter APIs to embed another Flutter engine in it.

macos/Runner/MainFlutterWindow.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class MainFlutterWindow: NSWindow {
  override func awakeFromNib() {
    let flutterViewController = FlutterViewController()
    let windowFrame = self.frame
    self.contentViewController = flutterViewController
    self.setFrame(windowFrame, display: true)

    RegisterGeneratedPlugins(registry: flutterViewController)

    super.awakeFromNib()

    openSecondaryWindow()
  }

  private func openSecondaryWindow() {
    // A new FlutterDartProject gives the controller a new engine, separate from the main window's.
    let project = FlutterDartProject()
    let flutterViewController = FlutterViewController(project: project)

    // A plain AppKit window to host the second engine's view.
    let secondaryWindow = NSWindow(
      contentRect: NSMakeRect(0, 0, 800, 600),
      styleMask: [.titled, .closable, .resizable, .miniaturizable],
      backing: .buffered,
      defer: false
    )
    secondaryWindow.contentViewController = flutterViewController
    secondaryWindow.title = "Secondary Window"
    secondaryWindow.setFrame(NSMakeRect(0, 0, 800, 600), display: true)
    secondaryWindow.makeKeyAndOrderFront(nil)
  }
}

openSecondaryWindow() creates a FlutterViewController from a new FlutterDartProject, which starts a second engine. It puts that controller in a plain NSWindow and shows the window.

Two overlapping macOS windows, the main window and “Secondary Window”. Both show “Flutter Demo Home Page” in the app bar, with the counter at 0.
Step 2: two windows, each running its own Flutter engine.

Now we get two windows that look the same, because both engines run their own copy of the same program. Each window has its own counter, and clicking + in one window does not change the other.

Before we can make them communicate, our Flutter program inside each engine needs to know which window it belongs to.

FlutterDartProject has a dartEntrypointArguments property for this:

macos/Runner/MainFlutterWindow.swift
1
2
3
4
5
6
private func openSecondaryWindow() {
  let project = FlutterDartProject()
  project.dartEntrypointArguments = ["secondary_window"]
  let flutterViewController = FlutterViewController(project: project)
  // ...
}

The engine passes these arguments to main(). Then we can read them and pick which app to run:

lib/main.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void main(List<String> arguments) {
  if (arguments.isNotEmpty && arguments[0] == 'secondary_window') {
    secondaryWindow();
  } else {
    mainWindow();
  }
}

void mainWindow() {
  runApp(const MyApp());
}

void secondaryWindow() {
  runApp(const MySecondaryApp());
}

The main window still runs the existing MyApp. The second window runs the new MySecondaryApp because it receives the secondary_window argument:

lib/main.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class MySecondaryApp extends StatelessWidget {
  const MySecondaryApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: .fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const MyHomePage(title: 'Secondary Window'),
    );
  }
}

The two windows now show different titles, and their counters still change independently.

Press + in either window. Each counter changes independently.

Screenshots of the app. Run the demo to start both Flutter windows.

flutter_multi_window_app
The main window, titled “Flutter Demo Home Page”, with the counter at 2.
Secondary Window
The second window, titled “Secondary Window”, with its own counter at 4.

Step 3: Basic Communication

Now we connect the two engines, so a click in the main window also updates the counter in the second window.

The connection has three parts:

  1. A native bridge that forwards messages from one engine to the other.
  2. A Dart side that sends the message.
  3. A Dart side that receives the message.

The Native Bridge

The bridge uses two channel names. Dart sends on FlutterToBridge and receives on BridgeToFlutter. The native side connects the two names across engines:

macos/Runner/CommunicationBridge.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import FlutterMacOS

func setupCommunicationBridge(sendingMessenger: FlutterBinaryMessenger, receivingMessenger: FlutterBinaryMessenger) {
  // The channel the sending engine's Dart code sends on.
  let sendChannel = FlutterBasicMessageChannel(name: "FlutterToBridge", binaryMessenger: sendingMessenger)
  // The channel the receiving engine's Dart code listens on.
  let receiveChannel = FlutterBasicMessageChannel(name: "BridgeToFlutter", binaryMessenger: receivingMessenger)

  sendChannel.setMessageHandler { message, reply in
    // Forward the message unchanged to the other engine.
    receiveChannel.sendMessage(message) { response in
      // Pass the receiver's answer back to the sender.
      reply(response)
    }
  }
}

When a message arrives on FlutterToBridge from the sending engine, the handler sends the same message on BridgeToFlutter to the receiving engine. The receiver's response goes back to the sender as the reply.

To use the bridge, the runner needs the messenger of each engine. openSecondaryWindow() now returns the engine of the second window:

macos/Runner/MainFlutterWindow.swift
1
2
3
4
5
private func openSecondaryWindow() -> FlutterEngine {
  // ...
  secondaryWindow.makeKeyAndOrderFront(nil)
  return flutterViewController.engine
}

Then awakeFromNib() gets a messenger from each engine and connects the main window to the secondary window:

macos/Runner/MainFlutterWindow.swift
1
2
3
4
5
6
7
8
9
10
11
override func awakeFromNib() {
  // ...
  super.awakeFromNib()

  let secondaryEngine = openSecondaryWindow()

  // A registrar gives access to an engine's messenger. "CommunicationBridge" is only a name for it.
  let mainMessenger = flutterViewController.engine.registrar(forPlugin: "CommunicationBridge").messenger
  let secondaryMessenger = secondaryEngine.registrar(forPlugin: "CommunicationBridge").messenger
  setupCommunicationBridge(sendingMessenger: mainMessenger, receivingMessenger: secondaryMessenger)
}

The Dart Side

We wrap the two channels in two functions, one to send and one to receive:

lib/communication_bridge.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import 'package:flutter/services.dart';

// Encodes messages to bytes. It must match the codec on the native side.
final _codec = StandardMessageCodec();

// Sends a message to the native bridge, which forwards it to the other engine.
// Completes with the other engine's reply.
Future<Object?> sendToBridge(Object? message) async {
  final sendChannel = BasicMessageChannel('FlutterToBridge', _codec);
  return await sendChannel.send(message);
}

// Calls onReceive for each message the bridge forwards from the other engine.
// Its return value becomes the reply.
void setBridgeMessageHandler(Future<Object?> Function(Object?) onReceive) {
  final receiveChannel = BasicMessageChannel('BridgeToFlutter', _codec);
  receiveChannel.setMessageHandler((message) async {
    return await onReceive(message);
  });
}

The main window sends the new value each time the counter changes:

lib/main.dart
1
2
3
4
5
6
void _incrementCounter() {
  setState(() {
    _counter++;
  });
  sendToBridge(_counter);
}

The second window gets its own page, MySecondaryPage. In initState, it registers a handler that copies the received value into its own _counter:

lib/main.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class _MySecondaryPageState extends State<MySecondaryPage> {
  int _counter = 0;

  @override
  void initState() {
    super.initState();
    setBridgeMessageHandler((message) async {
      setState(() {
        _counter = message as int;
      });
      return null;
    });
  }

  // build() shows _counter, like MyHomePage, but without the button.
}

Press + in the main window. Both counters receive the same value.

Screenshots of the app. Run the demo to start both Flutter windows.

flutter_multi_window_app
The main window with the counter at 3 and a plus button.
Secondary Window
The second window, also at 3, with no plus button.

Click the button in the main window. The counter in the second window now changes to the same value.

Each window still has its own _counter. The difference is that the main window now sends every change as a message, and the second window applies it.

Step 4: Structured Messages

With messages working, we can replace the counter with something more advanced: a shopping cart. The add button adds a random item to the cart, and the delete button in each row removes that row from the cart.

Add or delete items in the main window. The secondary window receives the updated cart.

Screenshots of the app. Run the demo to start both Flutter windows.

flutter_multi_window_app
The main window with a six-item cart table, a delete button on each row, and a plus button.
Secondary Window
The second window with the same six items and no buttons.

Instead of sending an integer counter, we want to send our own UpdateCartEvent class, which holds the updated cart:

lib/main.dart
1
2
- sendToBridge(_counter);
+ sendToBridge(UpdateCartEvent(items: _cartItems));

However, StandardMessageCodec only handles built-in types such as numbers, strings, lists, and maps, so it cannot encode UpdateCartEvent. We'll need to either write a custom codec, or convert the event to a standard type before sending it.

Since the app will need JSON serialization for server-side communications anyway, it makes sense to also use JSON to serialize these messages.

We can use json_serializable to generate the toJson and fromJson methods for our data classes, and send the encoded JSON string.

lib/main.dart
1
2
- sendToBridge(UpdateCartEvent(items: _cartItems));
+ sendToBridge(jsonEncode(UpdateCartEvent(items: _cartItems).toJson()));

The second window can decode the JSON message into the same event class:

lib/main.dart
1
2
3
4
5
6
7
8
9
  setBridgeMessageHandler((message) async {
+   final json = jsonDecode(message as String);
+   final event = UpdateCartEvent.fromJson(json);
    setState(() {
-     _counter = message as int;
+     _cartItems = event.items;
    });
    return null;
  });

Before, each message was one number. Now, each message is a JSON string of the whole cart. With two items in the cart, the message looks like this:

JSON
1
2
3
4
5
6
{
  "items": [
    { "name": "Item 0", "quantity": 1, "unitPrice": 39.0, "totalPrice": 39.0 },
    { "name": "Item 1", "quantity": 3, "unitPrice": 7.0, "totalPrice": 21.0 }
  ]
}

Every add or delete sends the full cart again. Both engines run in the same app process, so even sending the whole cart on every change is fast.

The two windows now show the same cart, and the bridge carries only one event type, UpdateCartEvent. A real POS has many more pages. Every new event type needs code to encode, send, and decode it, and code that routes it to the part of the app that handles it.

Alternative Solutions

Official Flutter multi-window support did not exist when we built this system. Flutter has since introduced its Desktop Windowing API. It places multiple windows in one widget tree, so they can share application state without an inter-engine message bridge.

That approach still does not fit our use case. Both screens are in use at the same time, so each one needs its own focused input. One Flutter engine has a single global focus manager, so only one focus node across all of its windows can have focus at a time. If the customer taps a field on their screen, the cashier's input loses focus.

Community packages such as desktop_multi_window heavily inspired our implementation. The package uses a separate Flutter engine for each window and provides window management and communication between engines. However, it did not offer the level of control we needed over native windows, focus, and input handling. We built our own integration around the same multi-engine approach, with explicit messages to synchronize application state.

Our custom native integration gives us control over each window and its input handling, while separate engines keep their Flutter focus state independent. The trade-off is more engine resources, native code to maintain, and messages to keep the transaction synchronized.

Written by

Suphon Thanakornpakapong & Nut Pinyo

Softnetics Blog