Build guide · Flutter

Liquid glass in Flutter

BackdropFilter with a blur gives Flutter frost, not liquid glass. The bend needs a fragment shader applied with ImageFilter.shader, which Impeller supports on iOS and Android; everywhere else the same widget falls back to blur.

More about Flutter

This is the Flutter recipe the Meniscus MCP server gives coding agents: the shader, the widget that feeds it the body's rect in device pixels, grouping, and the fallback. It analyzes clean on Flutter 3.44 and renders aligned under Impeller.

Updated · the recipe the Meniscus MCP server returns for this medium

In short: ClipRSuperellipse + BackdropFilter per glass body; refraction through ImageFilter.shader (Impeller).

Limits: the bend needs Impeller (ImageFilter.shader on iOS and Android; check ImageFilter.isShaderFilterSupported); elsewhere BackdropFilter blur gives frost only. Spec numbers are logical px, but the shader works in device px from the screen origin: multiply the body's global rect, radius, bezel and displacement by the device pixel ratio.

A. Glass body structure

Structure per glass body:

dart
import 'dart:ui';                                        // ImageFilter
import 'package:flutter/material.dart';

ClipRSuperellipse(
  borderRadius: BorderRadius.circular(24),
  child: BackdropFilter(
    filter: ImageFilter.blur(sigmaX: 3, sigmaY: 3),     // frost; refraction version below
    child: DecoratedBox(
      decoration: ShapeDecoration(
        color: Colors.white.withValues(alpha: .15),       // fill
        shape: RoundedSuperellipseBorder(borderRadius: BorderRadius.circular(24)),   // no uniform border:
      ),                                                   // the rim is directional (GlassRim below)
      child: child,                                        // flat content
    ),
  ),
)
  • That is the frost skeleton. RefractiveGlass below is the whole body: the bend where Impeller runs the shader, the same frost elsewhere, the directional rim (GlassRim), and outside the clip the ambient shadow and the 1 px edge line (GlassOutside). The shadow has the body cut out of it: a plain BoxShadow under the body is read back through the backdrop and greys the glass.
  • Keep children flat, gaps ≥ 8 px, and one BackdropFilter per glass body (each is a render pass). Bodies that share one backdrop (a tab bar and its search lens) read it once inside a BackdropGroup with BackdropFilter.grouped.

B. Refraction shader and the glass widget

BackdropFilter(filter: ImageFilter.shader(...)) with this port of the web shader (Impeller only). Register it in pubspec.yaml (flutter: shaders: - shaders/glass.frag). Built into an Android APK (Vulkan stage) on Flutter 3.44.2, and rendered with flutter test --enable-impeller at device pixel ratio 2, light and dark, with and without the shader.

glsl
// shaders/glass.frag
#include <flutter/runtime_effect.glsl>
precision highp float;

uniform vec2 uRes;               // set by the engine: backdrop size, device px
uniform vec4 uRect;              // glass body: x, y, w, h in device px from the screen origin
uniform float uRadius, uBezel, uDisp, uFrost, uProfile;   // device px; profile 0 bevel, 1 convex, 2 rim
uniform float uRim;              // rim strength: 1 light, 0.7 dark
uniform vec4 uFill;              // the material's fill token: rgb, alpha = amount
uniform sampler2D uBackdrop;     // set by the engine: the backdrop

out vec4 fragColor;

float sdRoundBox(vec2 p, vec2 b, float r) { vec2 q = abs(p) - b + r; return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r; }
float hash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
vec3 tex(vec2 px) {
  vec2 uv = clamp(px / uRes, 0.0, 1.0);
#ifdef IMPELLER_TARGET_OPENGLES
  uv.y = 1.0 - uv.y;
#endif
  return texture(uBackdrop, uv).rgb;
}

float bendAt(float s) {                                                 // shift across the bezel, edge = 1
  float a = 1.0 - s;
  if (uProfile > 0.5 && uProfile < 1.5) return a * (1.0 + a) * 0.5;    // convex dome
  if (uProfile > 1.5) { float u = max(1.0 - s / 0.35, 0.0); return u * u; } // rim: outer 35 %
  return a * a;                                                         // bevel
}

void main() {
  vec2 px = FlutterFragCoord().xy;
  vec2 c = uRect.xy + uRect.zw * 0.5, hb = uRect.zw * 0.5;
  float d = sdRoundBox(px - c, hb, uRadius);
  vec3 back = tex(px), col = back;
  if (d < 1.0) {
    float depth = clamp(-d / uBezel, 0.0, 1.0);
    vec2 e = vec2(0.5, 0.0);
    vec2 n = normalize(vec2(sdRoundBox(px - c + e.xy, hb, uRadius) - sdRoundBox(px - c - e.xy, hb, uRadius),
                            sdRoundBox(px - c + e.yx, hb, uRadius) - sdRoundBox(px - c - e.yx, hb, uRadius)));
    float bend = depth < 1.0 ? bendAt(depth) : 0.0;
    vec2 off = -n * bend * uDisp;                                       // inward
    off += (vec2(hash(px), hash(px + 17.0)) - 0.5) * 1.5 * uFrost;
    float k = 0.02 * bend * bend;                                       // dispersion stays at the rim
    vec3 bent = vec3(tex(px + off * (1.0 - k)).r, tex(px + off).g, tex(px + off * (1.0 + k)).b);
    vec3 blur = (tex(px + off + vec2(2.0, 0.0)) + tex(px + off - vec2(2.0, 0.0)) +
                 tex(px + off + vec2(0.0, 2.0)) + tex(px + off - vec2(0.0, 2.0))) * 0.25;
    vec3 g = mix(bent, blur, 0.35 * uFrost);
    g = mix(g, vec3(dot(g, vec3(0.299, 0.587, 0.114))), -0.4);          // saturation ×1.4
    g = mix(g, uFill.rgb, uFill.a);                                     // fill
    vec2 L = normalize(vec2(-1.0, -1.0));                               // key light, top-left
    float facing = dot(n, L);
    float rim = 1.0 - smoothstep(0.0, 1.5, -d);
    g += uRim * rim * mix(0.5, 0.9, max(facing, 0.0)) * (facing > 0.0 ? 1.0 : 0.55);
    g += uRim * (1.0 - smoothstep(0.0, 0.35, depth)) * max(facing, 0.0) * 0.18;
    col = mix(back, g, clamp(0.5 - d, 0.0, 1.0));
  }
  fragColor = vec4(col, 1.0);
}
dart
import 'dart:ui' as ui;
import 'package:flutter/material.dart';

ui.FragmentProgram? _glass;                         // await loadGlass() before runApp
Future<void> loadGlass() async => _glass ??= await ui.FragmentProgram.fromAsset('shaders/glass.frag');

/// One glass body: the bend through the shader where Impeller runs it, else frost (blur, fill and a painted rim);
/// the shadow and the edge line outside it either way. Content in `child` stays flat.
class RefractiveGlass extends StatefulWidget {
  const RefractiveGlass({super.key, required this.radius, required this.child, this.bezel = 22,
      this.displacement = 9, this.frost = 0.3, this.profile = 0, this.fallbackSigma = 4,
      this.fill = const Color(0x26FFFFFF), this.dark = false, this.shadow = true, this.grouped = false});
  final double radius, bezel, displacement, profile;  // logical px: bezel ≤ radius, displacement 0.4 × bezel
                                                      // (bevel) or 0.5 × radius (convex circle)
  final double frost;           // shader grain and blur, 0–1: lens 0.1, regular 0.3, frost 0.8
  final double fallbackSigma;   // blur where the shader is unavailable: lens 2, regular 4, frost 10
  final Color fill;             // the material's fill token for the theme: lens white 6 %, regular 15 %, frost 28 %
                                // (dark: rgb 18 18 24 at 14 / 30 / 40 %)
  final bool dark;              // dark theme: dimmer rim, stronger edge line and shadow
  final bool shadow;            // the ambient shadow: a floating bar yes, a pill inside it no
  final bool grouped;           // inside a BackdropGroup: share one backdrop read with the other bodies
  final Widget child;

  @override
  State<RefractiveGlass> createState() => _RefractiveGlassState();
}

class _RefractiveGlassState extends State<RefractiveGlass> {
  Rect? _rect;                                      // this body on screen, device px
  bool _pending = false;

  // The shader needs where the body is, which is known only after layout: measure after the frame, rebuild on change.
  void _measure(Duration _) {
    _pending = false;
    final box = mounted ? context.findRenderObject() as RenderBox? : null;
    if (box == null || !box.hasSize) return;
    final dpr = MediaQuery.devicePixelRatioOf(context);
    final rect = (box.localToGlobal(Offset.zero) * dpr) & (box.size * dpr);
    if (rect != _rect) setState(() => _rect = rect);
  }

  @override
  Widget build(BuildContext context) {
    if (!_pending) {
      _pending = true;
      WidgetsBinding.instance.addPostFrameCallback(_measure);
    }
    final dpr = MediaQuery.devicePixelRatioOf(context), r = _rect, w = widget;
    // Flutter has no reduce-transparency flag; Increase Contrast stands in: the theme's solid surface, no bend, and a
    // stronger edge line (a pill on a bar then reads from its edge and the accent label).
    final contrast = MediaQuery.highContrastOf(context);
    final fill = contrast ? (w.dark ? const Color(0xF024242A) : const Color(0xEBF5F5F7)) : w.fill;
    final bend = !contrast && _glass != null && ui.ImageFilter.isShaderFilterSupported && r != null;
    ui.ImageFilter filter = ui.ImageFilter.blur(sigmaX: w.fallbackSigma, sigmaY: w.fallbackSigma);   // frost fallback
    if (bend) {
      final shader = _glass!.fragmentShader();
      var i = 2;                                    // floats 0–1 are uRes, set by the engine
      for (final v in [r.left, r.top, r.width, r.height, w.radius * dpr, w.bezel * dpr, w.displacement * dpr,
          w.frost, w.profile, w.dark ? .7 : 1, fill.r, fill.g, fill.b, fill.a]) {
        shader.setFloat(i++, v.toDouble());
      }
      filter = ui.ImageFilter.shader(shader);
    }
    // The shader draws the fill and the rim itself; the fallback paints them over its blur.
    final content = bend ? w.child : CustomPaint(
      foregroundPainter: GlassRim(w.radius, dark: w.dark),
      child: DecoratedBox(
        decoration: ShapeDecoration(color: fill, shape: RoundedSuperellipseBorder(borderRadius: BorderRadius.circular(w.radius))),
        child: w.child),
    );
    final body = w.grouped ? BackdropFilter.grouped(filter: filter, child: content) : BackdropFilter(filter: filter, child: content);
    return CustomPaint(
      painter: GlassOutside(w.radius, dark: w.dark, shadow: w.shadow, contrast: contrast),
      child: ClipRSuperellipse(borderRadius: BorderRadius.circular(w.radius), child: body),
    );
  }
}

Path _shape(Rect rect, double radius) => RoundedSuperellipseBorder(borderRadius: BorderRadius.circular(radius)).getOuterPath(rect);

/// The fallback's 1 px rim: brightest top-left (key light), dimmer bottom-right (counter-light), faint flanks.
class GlassRim extends CustomPainter {
  GlassRim(this.radius, {this.dark = false});
  final double radius;
  final bool dark;

  @override
  void paint(Canvas canvas, Size size) {
    final rect = (Offset.zero & size).deflate(.5);
    canvas.drawPath(_shape(rect, radius - .5), Paint()
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1
      ..shader = LinearGradient(begin: Alignment.topLeft, end: Alignment.bottomRight, stops: const [0, .35, .65, 1],
          colors: [for (final a in dark ? [.68, .2, .2, .35] : [.96, .2, .2, .56]) Colors.white.withValues(alpha: a)])
          .createShader(rect));
  }

  @override
  bool shouldRepaint(GlassRim old) => old.radius != radius || old.dark != dark;
}

/// Outside the body: the ambient shadow with the body cut out (a shadow under the glass is read back through the
/// backdrop and greys it, so a plain BoxShadow will not do) and the 1 px edge line just outside the rim.
class GlassOutside extends CustomPainter {
  GlassOutside(this.radius, {this.dark = false, this.shadow = true, this.contrast = false});
  final double radius;
  final bool dark, shadow, contrast;

  @override
  void paint(Canvas canvas, Size size) {
    final rect = Offset.zero & size, body = _shape(rect, radius);
    if (shadow) {
      canvas.save();
      canvas.clipPath(Path()..fillType = PathFillType.evenOdd..addRect(rect.inflate(96))..addPath(body, Offset.zero));
      canvas.drawPath(body.shift(const Offset(0, 8)), Paint()
        ..color = Colors.black.withValues(alpha: dark ? .35 : .14)
        ..maskFilter = const MaskFilter.blur(BlurStyle.normal, 14));
      canvas.restore();
    }
    canvas.drawPath(_shape(rect.inflate(.5), radius + .5), Paint()
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1
      ..color = contrast ? (dark ? Colors.white.withValues(alpha: .35) : Colors.black.withValues(alpha: .2))
          : Colors.black.withValues(alpha: dark ? .32 : .12));
  }

  @override
  bool shouldRepaint(GlassOutside old) => old.radius != radius || old.dark != dark || old.shadow != shadow || old.contrast != contrast;
}
  • Uniforms are float, vecN and sampler2D only: an int passes the Metal stage and fails the Android Vulkan stage (Non-floating-type struct member). Porting from WebGL: varying/gl_FragCoord → FlutterFragCoord(), texture2D → texture, gl_FragColor → an out vec4.
  • A shader body inside another body's child gets that body's coordinates, not the screen's, and draws its rim in the wrong place: lay the pill (or any lens on a bar) over the bar as a sibling in a Stack, as above.
  • Flutter has no reduce-transparency flag: MediaQuery.highContrastOf stands in (a near-opaque fill, no bend). Nor does it see the iOS 27 clear-to-tinted setting: check screenshots with the fills halved and doubled.
  • Headless check: flutter test --enable-impeller runs the shader on macOS; pump the screen over a grid and save RenderRepaintBoundary.toImage as a PNG to see the bend without a device.
  • Materialize: animate displacement, the fill's alpha and uRim from 0 to their values over 200–300 ms (ease-out) instead of fading opacity; a cross-fade under MediaQuery.disableAnimationsOf. Touch illumination: while pressed, paint a RadialGradient (white 35 % → 0) centred on the touch point over the body, and a quarter of it on glass within 24 px. Background extension: under a floating sidebar, the hero's edge flipped (Transform.flip(flipX: true)) and blurred (ImageFiltered, sigma 16), so the sidebar bends a continuation of the hero.
  • The first frame is frost; the measured rect arrives one frame later. A body that moves without rebuilding (it scrolls, or an ancestor animates its position) keeps its old rect until it rebuilds, so rebuild it from the scroll or animation listener. Content scrolling under a fixed bar needs nothing.

C. Tab bar with a pill and a search lens

dart
import 'package:flutter/material.dart';
import 'glass.dart';                                  // RefractiveGlass (B)

/// A floating tab bar: a regular capsule, its moving lens pill and, when the app has search or one prominent action,
/// a separate circular lens. The bar and the lens read one backdrop; the pill is a body of its own laid over the bar
/// (a shader body inside another body's child gets that body's coordinates). Pressing a tab grows the pill's bend
/// 15 %. Put it in a Stack over content that scrolls under it, 8–16 above the safe area.
class GlassTabBar extends StatefulWidget {
  const GlassTabBar({super.key, required this.tabs, required this.selected, required this.onSelect, this.searchIcon,
      this.onSearch, this.dark = false});
  final List<Widget> tabs;
  final int selected;
  final ValueChanged<int> onSelect;
  final Widget? searchIcon;                         // null: no search lens
  final VoidCallback? onSearch;
  final bool dark;

  @override
  State<GlassTabBar> createState() => _GlassTabBarState();
}

class _GlassTabBarState extends State<GlassTabBar> {
  bool _pressed = false;

  @override
  Widget build(BuildContext context) {
    final w = widget, dark = w.dark;
    final still = MediaQuery.disableAnimationsOf(context);
    return SizedBox(
      height: 60,
      child: BackdropGroup(
        child: Row(children: [
          Expanded(child: LayoutBuilder(builder: (context, c) {
            final itemW = (c.maxWidth - 8) / w.tabs.length;
            return Stack(children: [
              Positioned.fill(child: RefractiveGlass(radius: 30, grouped: true, dark: dark,
                  fill: dark ? const Color(0x4D121218) : const Color(0x26FFFFFF),            // regular
                  child: const SizedBox.expand())),
              // The one lens on the bar. Animated, it rebuilds every frame and so re-measures where it is.
              TweenAnimationBuilder<double>(
                tween: Tween(end: w.selected.toDouble()),
                duration: still ? Duration.zero : const Duration(milliseconds: 380),
                curve: Curves.easeOutCubic,
                builder: (context, t, _) => Positioned(left: 4 + t * itemW, top: 4, width: itemW, height: 52,
                    child: AnimatedScale(scale: _pressed ? 1.04 : 1, duration: still ? Duration.zero : const Duration(milliseconds: 160),
                        child: RefractiveGlass(radius: 26, bezel: 26, displacement: 10.4 * (_pressed ? 1.15 : 1), frost: .1,
                            fallbackSigma: 2, shadow: false, dark: dark,
                            fill: dark ? const Color(0x1FFFFFFF) : const Color(0x47FFFFFF),   // pill
                            child: const SizedBox.expand()))),
              ),
              Positioned.fill(left: 4, right: 4, child: Row(children: [
                for (var i = 0; i < w.tabs.length; i++)
                  Expanded(child: Semantics(
                    button: true,
                    selected: i == w.selected,
                    child: GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTapDown: (_) => setState(() => _pressed = true),
                      onTapUp: (_) => setState(() => _pressed = false),
                      onTapCancel: () => setState(() => _pressed = false),
                      onTap: () => w.onSelect(i),
                      child: w.tabs[i],
                    ),
                  )),
              ])),
            ]);
          })),
          if (w.searchIcon != null) ...[
            const SizedBox(width: 12),
            SizedBox.square(dimension: 60,                              // a circle: bezel = radius, displacement 0.5 × radius
                child: RefractiveGlass(radius: 30, bezel: 30, displacement: 15, profile: 1, frost: .1, fallbackSigma: 2,
                    grouped: true, dark: dark, fill: dark ? const Color(0x24121218) : const Color(0x0FFFFFFF),   // lens
                    child: Semantics(button: true, label: 'Search',
                        child: GestureDetector(behavior: HitTestBehavior.opaque, onTap: w.onSearch, child: Center(child: w.searchIcon))))),
          ],
        ]),
      ),
    );
  }
}

D. Liquid metal accent (not glass)

One metal element per view: a sweep-gradient rim painted over an opaque face, CustomPaint(foregroundPainter: MetalRim(), child: …).

dart
class MetalRim extends CustomPainter {
  MetalRim({this.width = 3, this.turn = 0});
  final double width, turn; // turn 0..1; animate slowly (about 12 s per turn), hold still under reduced motion

  @override
  void paint(Canvas canvas, Size size) {
    final rect = Offset.zero & size;
    final rrect = RRect.fromRectAndRadius(rect.deflate(width / 2), Radius.circular(size.height / 2));
    canvas.drawRRect(
      rrect,
      Paint()
        ..style = PaintingStyle.stroke
        ..strokeWidth = width
        ..shader = SweepGradient(
          transform: GradientRotation((200 / 360 + turn) * 2 * math.pi),
          colors: const [Color(0xFF14151A), Color(0xFFF7F8FC), Color(0xFF8A8D96), Color(0xFFFFFFFF),
                         Color(0xFF2A2B30), Color(0xFFD9DBE2), Color(0xFF14151A), Color(0xFFF7F8FC)],
          stops: const [0.0, 0.10, 0.30, 0.45, 0.55, 0.70, 0.81, 0.92],
        ).createShader(rect),
    );
  }

  @override
  bool shouldRepaint(MetalRim old) => old.turn != turn || old.width != width;
}
  • import 'dart:math' as math; for math.pi and import 'package:flutter/widgets.dart';.
  • Flowing bands and red/blue fringes: port the web liquidMetal shader to a FragmentProgram (#include <flutter/runtime_effect.glsl>, FlutterFragCoord()) and paint the shape with Paint()..shader = program.fragmentShader(); it samples nothing behind, so no BackdropFilter. Replace its discard with fragColor = vec4(0.0); return; — SkSL rejects discard, so the shader would not load on Skia.

E. Border beam (animated rim light)

One beamed element per view (border-beam effect spec): PathMetric.extractPath along the shape's outline, so the beam keeps one speed and length on any ShapeBorder. Analysed and golden-rendered on Flutter 3.44.

dart
import 'dart:math' as math;
import 'dart:ui' as ui;

import 'package:flutter/widgets.dart';

/// A short arc of light travelling along [shape] at constant speed
/// (PathMetric slices, not a rotating gradient).
class BorderBeam extends StatefulWidget {
  const BorderBeam({
    super.key,
    required this.shape,
    required this.child,
    this.lap = const Duration(seconds: 5), // 4–6 s buttons, 6–10 s cards, 2–3 s while working
    this.tail = 0.25, // fraction of the perimeter
    this.width = 1.5, // = rim width
    this.color = const Color(0xFFFFFFFF), // accent on light glass
    this.bloom = 4, // blur sigma of the glow copy; 0 = none
    this.starts = const [0.0], // [0.0, 0.5] for twin beams
  });

  final ShapeBorder shape;
  final Widget child;
  final Duration lap;
  final double tail, width, bloom;
  final Color color;
  final List<double> starts;

  @override
  State<BorderBeam> createState() => _BorderBeamState();
}

class _BorderBeamState extends State<BorderBeam> with SingleTickerProviderStateMixin {
  late final AnimationController _lap = AnimationController(vsync: this, duration: widget.lap);

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    if (MediaQuery.disableAnimationsOf(context)) {
      _lap.stop();
    } else if (!_lap.isAnimating) {
      _lap.repeat();
    }
  }

  @override
  void dispose() {
    _lap.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (MediaQuery.disableAnimationsOf(context)) return widget.child; // reduced motion: no beam
    return CustomPaint(foregroundPainter: _BeamPainter(_lap, widget), child: widget.child);
  }
}

class _BeamPainter extends CustomPainter {
  _BeamPainter(this.lap, this.beam) : super(repaint: lap);
  final Animation<double> lap;
  final BorderBeam beam;
  ui.PathMetric? _outline;
  Size? _size;

  @override
  void paint(Canvas canvas, Size size) {
    if (size != _size) {
      _size = size; // the outline only changes with the size
      _outline = beam.shape.getOuterPath((Offset.zero & size).deflate(beam.width / 2)).computeMetrics().first;
    }
    final outline = _outline!;
    if (beam.bloom > 0) {
      // One blur pass for all slices: a layer blurred on restore.
      final glow = Paint()
        ..imageFilter = ui.ImageFilter.blur(sigmaX: beam.bloom, sigmaY: beam.bloom)
        ..color = const Color(0xCC000000); // layer opacity 80 %
      canvas.saveLayer((Offset.zero & size).inflate(beam.bloom * 3), glow);
      _slices(canvas, outline, beam.width * 2);
      canvas.restore();
    }
    _slices(canvas, outline, beam.width);
  }

  /// The tail as n nested strokes that all end at the head: stroke k starts k/n of the tail behind it, so
  /// opacity builds up toward the head with no seams between pieces.
  void _slices(Canvas canvas, ui.PathMetric outline, double strokeWidth) {
    const n = 16;
    final len = outline.length, tail = beam.tail * len;
    double target(int k) => k < 0 ? 0 : math.pow((k + 1) / n, 2).toDouble(); // opacity in the k-th piece
    for (final start in beam.starts) {
      final head = ((lap.value + start) % 1) * len;
      for (var k = 0; k < n; k++) {
        final alpha = 1 - (1 - target(k)) / (1 - target(k - 1));
        final paint = Paint()
          ..style = PaintingStyle.stroke
          ..strokeWidth = strokeWidth
          ..color = beam.color.withValues(alpha: alpha);
        for (final (from, to) in _wrapped(head - tail * (n - k) / n, head, len)) {
          canvas.drawPath(outline.extractPath(from, to), paint);
        }
      }
    }
  }

  static List<(double, double)> _wrapped(double a, double b, double len) =>
      b <= 0 ? [(a + len, b + len)] : a < 0 ? [(a + len, len), (0, b)] : [(a, b)];

  @override
  bool shouldRepaint(_BeamPainter old) => old.beam != beam;
}

Usage: BorderBeam(shape: const StadiumBorder(), child: glassButton); a card BorderBeam(shape: RoundedSuperellipseBorder(borderRadius: BorderRadius.circular(28)), lap: const Duration(seconds: 8), starts: const [0, .5], child: glassCard).

  • The shape must be the glass body's own shape, so the beam lies on its rim; it paints above the child, inside the outline by half its width.
  • Light glass: color: const Color(0xFF2B6BFF), width: 2.
  • Not a SweepGradient rotated with GradientRotation: that is angle-driven and crawls mid-edge, then races round the caps.

QA. Check it

  • flutter analyze, then flutter build apk --debug: the APK build runs the Android Vulkan stage of the shader compiler, the one that rejects int uniforms. flutter build ios --simulator --no-codesign runs the Metal stage.
  • Headless, with the real shader: flutter test --enable-impeller runs Impeller on macOS. This test pumps the glass over a grid and saves a PNG per theme; look at it for the bend, the rim and doubled lines (pass frost: 0 to see the bend without the shader's blur). Pump your own screen in place of the tab bar (one with its own photo works too). Text draws as boxes there (the test font); judge label contrast on a device or simulator.
dart
// test/glass_probe_test.dart — flutter test --enable-impeller test/glass_probe_test.dart
// Renders the glass over a grid with the real shader (flutter test runs Impeller on macOS) and saves
// probe-light.png and probe-dark.png: lines must bend inside every bezel, the rim is brighter top-left, nothing doubles.
import 'dart:io';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:your_app/glass.dart';
import 'package:your_app/tab_bar.dart';

class Grid extends CustomPainter {
  Grid(this.dark);
  final bool dark;

  @override
  void paint(Canvas canvas, Size size) {
    canvas.drawRect(Offset.zero & size, Paint()..shader = LinearGradient(begin: Alignment.topLeft, end: Alignment.bottomRight,
        colors: dark ? const [Color(0xFF1B2A4A), Color(0xFF4A1B3A)] : const [Color(0xFFFFB46B), Color(0xFF6BB5FF)])
        .createShader(Offset.zero & size));
    final line = Paint()..color = dark ? Colors.white70 : Colors.black87..strokeWidth = 1.5;
    for (double x = 0; x < size.width; x += 14) { canvas.drawLine(Offset(x, 0), Offset(x, size.height), line); }
    for (double y = 0; y < size.height; y += 14) { canvas.drawLine(Offset(0, y), Offset(size.width, y), line); }
  }

  @override
  bool shouldRepaint(Grid old) => old.dark != dark;
}

void main() {
  for (final dark in [false, true]) {
    testWidgets('glass ${dark ? 'dark' : 'light'}', (tester) async {
      tester.view.physicalSize = const Size(780, 400);            // 390 × 200 logical at 2×
      tester.view.devicePixelRatio = 2;
      addTearDown(tester.view.reset);
      await tester.runAsync(loadGlass);
      expect(ui.ImageFilter.isShaderFilterSupported, isTrue, reason: 'run with --enable-impeller');
      final ink = dark ? Colors.white : const Color(0xFF1D1D1F);
      final key = GlobalKey();
      // The piece under test over the grid; a screen with its own photo works too.
      await tester.pumpWidget(MaterialApp(debugShowCheckedModeBanner: false, home: Material(type: MaterialType.transparency, child: RepaintBoundary(key: key, child: Stack(children: [
        Positioned.fill(child: CustomPaint(painter: Grid(dark))),
        Positioned(left: 20, right: 20, bottom: 40, child: GlassTabBar(dark: dark, selected: 1, onSelect: (_) {},
            searchIcon: Icon(Icons.search, color: ink),
            tabs: [for (final l in ['Home', 'Photos', 'Map', 'More']) Center(child: Text(l, style: TextStyle(color: ink, fontSize: 11, fontWeight: FontWeight.w600)))])),
      ])))));
      await tester.pump();                                         // the glass measures its rect after the first frame
      await tester.pump(const Duration(milliseconds: 500));
      final boundary = key.currentContext!.findRenderObject()! as RenderRepaintBoundary;
      await tester.runAsync(() async {
        final png = await (await boundary.toImage(pixelRatio: 2)).toByteData(format: ui.ImageByteFormat.png);
        File('probe-${dark ? 'dark' : 'light'}.png').writeAsBytesSync(png!.buffer.asUint8List());
      });
    });
  }
}
  • On a device or simulator (Impeller is the default on iOS and Android): screenshot light and dark, then turn on Increase Contrast (MediaQuery.highContrastOf stands in for reduced transparency) and Reduce Motion.

<!-- medium: react-native -->

Questions

Do I need a package for liquid glass in Flutter?

No. A fragment shader and a small widget are enough, as below; packages such as liquid_glass_renderer do the same with their own API.

Does it work on Android?

Yes, under Impeller (the default on recent Flutter for Android). Check ImageFilter.isShaderFilterSupported; where it is false, the widget shows the blur fallback.

Why does my glass sample the wrong part of the screen?

The shader works in device pixels from the screen origin. Multiply the body's global rect, radius, bezel and displacement by the device pixel ratio.

The rules behind it

The code is half of it. Where glass belongs, which material each body gets, how it stays legible and what to reject are in the liquid glass guide and the 34 component specs. Other platforms: CSS and web, SwiftUI, React Native, Figma.