Embedding Flutter in “web-native” applications

Arne Molland
2 min readJan 8, 2021

--

Sometimes, there’s a Flutter widget, component, or even entire apps that you want to embed into an existing web page or application. While Flutter for the web is still in beta, it’s never too early to play around with the possibilities of using Flutter for creating cool experiences on the web.

Disclaimer: This approach is a workaround until Flutter itself is wrapped in a web component, and is based on Rody Davis’ hack found here.

The problem

The current implementation of Flutter for web overrides the body element in your DOM, making it impossible by default to embed Flutter as a component. I encountered this issue when I was building my portfolio, where I’m showcasing demo applications rendered live in the browser.

While it’s straight-forward in a Flutter-only web application, it’s harder to integrate into an existing web project.

The solution

Since we can’t work around Flutter overriding the <body> element, we can define a custom HTML element that has its own <body> element available for Flutter to use freely, and wrap it in an <iframe> to avoid collisions. To define a custom HTML element, we first create the markup in an HTML file:

And to define the element, we’ll need some JavaScript:

At the baseline, all we’re doing is extending the HTMLElement class and returning an <iframe> fetching our app.html file which in turn mounts our Flutter instance.

To weave this together with our existing website, we’ll just import the custom element definition and we’re good to use our Flutter instance as a web component, wherever we like!

To finish this off, we just need to build our flutter project using flutter build web and move the output main.dart.js and other static files e.g. assets and manifest.json into the same directory as our web content, and we’re good to go.

Tip: you can use any task runner/module bundler to automate this process.

The result 🎉

The Flutter demo application is now embedded in an existing website. While the demo is pure HTML/CSS/JS, the principle is the same for React, Vue, Svelte, and beyond.

--

--

Arne Molland
Arne Molland

Written by Arne Molland

CTO @ Gameflow. Writing about things I find cool.

Responses (1)