Skip to content
Blog

Embedding three.js in Flutter Web: A Scene You Can Point At

Embed a three.js scene in a Flutter web app with HtmlElementView and dart:js_interop: scene setup, shared input and gestures, LayoutBuilder sizing, device pixel ratio, and clean teardown.

Published on • November 11, 2026

AI Assistant

three.js is the usual answer when a Flutter web app needs a real 3D scene: a Scene, cameras, lights, geometries and materials, model loading, and orbit controls, all sitting on top of WebGL. The scene itself is plain JavaScript, so the job is mounting it beside Flutter’s widget tree, keeping input, sizing, and lifecycle consistent with the widgets around it.

The scene you are hosting

three.js ships as ES modules, so load it with an import map in web/index.html — from a CDN or from files you bundle yourself:

<script type="importmap">
{
  "imports": {
    "three": "/js/three.module.js",
    "three/addons/": "/js/addons/"
  }
}
</script>

The core objects are the ones the three.js manual walks through: a Scene, a PerspectiveCamera (or OrthographicCamera), and a WebGLRenderer — the newer WebGPURenderer is the same role with a WebGPU backend — plus lights, geometries, and materials. GLTFLoader loads models, OrbitControls handles camera input, and the render loop is a requestAnimationFrame callback:

import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';

export function initThree(width, height, onPointer) {
  const scene = new THREE.Scene();
  const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
  const renderer = new THREE.WebGLRenderer({ antialias: true });
  renderer.setSize(width, height);
  renderer.setPixelRatio(window.devicePixelRatio);

  const host = document.querySelector('#three-view-host');
  host.appendChild(renderer.domElement);

  scene.add(new THREE.AmbientLight(0xffffff, 0.6));
  new GLTFLoader().load('/models/robot.glb', (gltf) => scene.add(gltf.scene));
  const controls = new OrbitControls(camera, renderer.domElement);
  renderer.domElement.addEventListener('pointerdown', (e) => onPointer(e.offsetX, e.offsetY));

  let rafId = 0;
  const animate = () => { rafId = requestAnimationFrame(animate); renderer.render(scene, camera); };
  animate();

  return { scene, camera, renderer, controls, get rafId() { return rafId; } };
}

Mount it with an HtmlElementView

On the Dart side, register a view factory that creates the host element, declare the JS entry points with dart:js_interop, and keep the returned handle in a field — that handle is what you resize and dispose later:

import 'dart:js_interop';
import 'package:web/web.dart' as web;

@JS('initThree')
external JSObject initThree(double width, double height, JSFunction onPointer);

@JS('resizeThree')
external void resizeThree(JSObject handle, double width, double height, double dpr);

@JS('disposeThree')
external void disposeThree(JSObject handle);

Then build the view inside a LayoutBuilder so the scene follows Flutter’s layout instead of the window:

class _ThreeStageState extends State<ThreeStage> {
  JSObject? _scene;
  Size? _lastSize;

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (context, constraints) {
      final size = constraints.biggest;
      if (size != _lastSize) {
        _lastSize = size;
        final dpr = web.window.devicePixelRatio;
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (_scene == null) {
            _scene = initThree(size.width, size.height, onPointer.toJS);
          } else {
            resizeThree(_scene!, size.width, size.height, dpr);
          }
        });
      }
      return const HtmlElementView(viewType: 'three-view');
    });
  }

  void onPointer(double x, double y) {
    // Fired from JS: the canvas already consumed this event.
  }

  @override
  void dispose() {
    final scene = _scene;
    if (scene != null) disposeThree(scene);
    super.dispose();
  }
}

Give the stage bounded constraints — Expanded, SizedBox, or a fixed-height parent — because an unbounded LayoutBuilder hands you infinite size. The same code should also react to window resize and to devicePixelRatio changes: call resizeThree with the new values and let the renderer’s setPixelRatio keep the drawing buffer matched to the display.

Keep input working on both sides

Pointer events over the canvas go to the DOM element, not to Flutter: OrbitControls consumes them for the camera, and anything Flutter draws on top of the scene sees nothing. There are two fixes, and you usually need both. Bridge the events you care about into Dart with callbacks, as onPointer above does, and wrap Flutter overlays in IgnorePointer when the canvas should receive the click instead. The reverse case is documented in Flutter’s web content guide too — platform views can swallow pointer events intended for Flutter — so test your HUD buttons rather than assuming they fire.

Tear down and pause off-screen

A three.js scene owns GPU memory and a running loop, so disposeThree must cancel the requestAnimationFrame id, dispose controls, dispose every geometry and material the scene holds — traverse the tree and call dispose() on each — and finally call renderer.dispose(). Do this from the widget’s dispose(), and pause the loop whenever the view is off-screen or the tab is hidden: a scene behind a route or in a background tab should not be burning GPU cycles at 60 fps.

Takeaway: Mount three.js as a host element inside an HtmlElementView, hold the returned JSObject handle, let LayoutBuilder and devicePixelRatio drive resizes, bridge pointer events back into Dart, and cancel the loop plus dispose the renderer when the widget goes away.

Sources