+1 (415) 480-3939

Custom Visual Effects in Flutter with Fragment Shaders: GLSL, Uniforms, and Performance

Most Flutter UI is composed from widgets, but some effects are hard to build that way: animated gradients, ripples, noise, duotone filters, or a wipe transition. For these, Flutter lets you write a fragment shader in GLSL and run it on the GPU through FragmentProgram. This tutorial walks through a complete example: an animated gradient-wave background driven by time and touch position.

When a shader is the right tool

Use a shader when the effect is computed per pixel and would otherwise need many layered widgets or a heavy CustomPainter loop. Don't use one for ordinary layout, text, or simple opacity and blur, where built-in widgets are cheaper and easier to maintain.

Step 1: Write the shader

Create shaders/wave.frag. Flutter's shader support uses GLSL with the runtime_effect.glsl include. Check the current Flutter docs for the supported GLSL subset, because not every feature is available.

#version 460 core
#include <flutter/runtime_effect.glsl>

uniform vec2 uSize;
uniform float uTime;
uniform vec2 uTouch;

out vec4 fragColor;

void main() {
  vec2 uv = FlutterFragCoord().xy / uSize;
  float wave = sin(uv.x * 8.0 + uTime) * 0.05;
  float d = distance(uv, uTouch / uSize);
  float glow = smoothstep(0.35, 0.0, d);
  vec3 base = mix(vec3(0.05, 0.10, 0.30), vec3(0.10, 0.60, 0.90), uv.y + wave);
  fragColor = vec4(base + glow * 0.25, 1.0);
}

Uniforms are set from Dart in the order they are declared, and each float takes one slot (a vec2 takes two).

Step 2: Register the shader

Declare it in pubspec.yaml. The build compiles it for each platform:

flutter:
  shaders:
    - shaders/wave.frag

Step 3: Load it once

Loading is asynchronous and the result can be reused, so load it once and cache it rather than in build.

import 'dart:ui' as ui;

class WaveShader {
  static ui.FragmentProgram? _program;

  static Future<ui.FragmentShader> create() async {
    _program ??= await ui.FragmentProgram.fromAsset('shaders/wave.frag');
    return _program!.fragmentShader();
  }
}

Each call to fragmentShader() returns a new shader instance that shares the compiled program. Call dispose() on the instance when you finish with it.

Step 4: Paint with it

class WavePainter extends CustomPainter {
  WavePainter(this.shader, this.time, this.touch);
  final ui.FragmentShader shader;
  final double time;
  final Offset touch;

  @override
  void paint(Canvas canvas, Size size) {
    shader
      ..setFloat(0, size.width)
      ..setFloat(1, size.height)
      ..setFloat(2, time)
      ..setFloat(3, touch.dx)
      ..setFloat(4, touch.dy);
    canvas.drawRect(Offset.zero & size, Paint()..shader = shader);
  }

  @override
  bool shouldRepaint(WavePainter old) =>
      old.time != time || old.touch != touch;
}

Step 5: Animate it

Drive time from a Ticker and rebuild only the painter, using the repaint listenable rather than setState on the whole screen.

class WaveBackground extends StatefulWidget {
  const WaveBackground({super.key});
  @override
  State<WaveBackground> createState() => _WaveBackgroundState();
}

class _WaveBackgroundState extends State<WaveBackground>
    with SingleTickerProviderStateMixin {
  ui.FragmentShader? _shader;
  late final Ticker _ticker;
  final _time = ValueNotifier<double>(0);
  Offset _touch = const Offset(200, 200);

  @override
  void initState() {
    super.initState();
    WaveShader.create().then((s) => setState(() => _shader = s));
    _ticker = createTicker((d) => _time.value = d.inMicroseconds / 1e6)..start();
  }

  @override
  void dispose() {
    _ticker.dispose();
    _shader?.dispose();
    _time.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final shader = _shader;
    if (shader == null) return const ColoredBox(color: Color(0xFF0D1A4D));
    return GestureDetector(
      onPanUpdate: (d) => _touch = d.localPosition,
      child: ValueListenableBuilder<double>(
        valueListenable: _time,
        builder: (_, t, __) => CustomPaint(
          painter: WavePainter(shader, t, _touch),
          size: Size.infinite,
        ),
      ),
    );
  }
}

Note the placeholder colour while the shader loads. It avoids a flash of empty content and doubles as a fallback.

Step 6: Apply a shader to existing content

For filters over widgets rather than a generated background, you can sample a child image. Declare uniform sampler2D uImage; and use ImageFilter.shader (available in current stable Flutter) or ShaderMask. Samplers are set with setImageSampler, and the index counts samplers separately from floats. Verify API availability against the Flutter version you ship.

Performance checklist

  • Keep the math cheap. Avoid loops with large bounds and many texture reads; cost scales with pixel count.
  • Isolate repaints. Wrap the effect in a RepaintBoundary so the animation doesn't force surrounding widgets to repaint.
  • Profile on real devices. Use DevTools with a profile build. Emulators say little about GPU cost.
  • Stop when invisible. Pause the Ticker when the screen is off-route or the app is backgrounded (TickerMode does this for off-stage routes).
  • Respect reduced motion. Check MediaQuery.disableAnimationsOf(context) and render a static frame when it is true.
  • Warm up. If you see a first-use hitch, trigger one off-screen draw early, and confirm on a profile build whether it helps on your target renderer.

Common pitfalls

  1. Uniform order mismatch. Wrong index means silently wrong visuals. Keep a constant per index.
  2. Hot reload and shaders. Edits to .frag files are picked up on hot restart, not always hot reload; restart if nothing changes.
  3. Platform support. Shader support varies by renderer and target, notably on web. Test every platform you ship and keep a non-shader fallback.
  4. Coordinate space. FlutterFragCoord() is in the local pixel space of the painted area. Pass in the real size and account for device pixel ratio when passing touch positions.

Testing

Golden tests can render a shader-backed widget at a fixed time, so make time an input and not a global clock. Pin the value, and run goldens on the same platform that generated them.

Wrapping up

Fragment shaders give Flutter apps distinctive visuals without adding native code. Keep effects small, drive them with explicit uniforms, isolate repaints, and always ship a fallback. If your team is planning a polished, brand-specific UI and wants senior Flutter engineers to build or review it, get in touch.