Learn/Advanced UI/Impeller & Custom GPU Shaders (GLSL)

Impeller & Custom GPU Shaders (GLSL)

Unlock cinematic visual effects in Flutter using GLSL fragment shaders and Impeller

15 min~6 min read+60 FX

You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.

Table of Contents

  1. 1. 1. What is a Fragment Shader?
  2. 2. 2. Writing Your First GLSL Shader (`wave.frag`)
  3. 3. 3. Wiring the Shader into Flutter
  4. 4. This Lesson In Simple Words
  5. 5. Your level focus
  6. 6. One practical habit
  7. 7. Deep Understanding Guide
  8. 8. Why this lesson matters
  9. 9. Study flow for better retention
  10. 10. Architecture Lens

Having trouble? AI is here to help

Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.

Use the AI button at the bottom of the screen

Impeller & Custom GPU Shaders (GLSL)

Flutter's rendering engine rewrite—Impeller—brings unprecedented graphics capabilities to mobile applications. With Impeller's first-class support for custom fragment shaders, developers can create cinematic visual effects: liquid glass reflections, animated mesh gradients, water ripples, and chromatic aberrations that run at a rock-solid 120 FPS.

In this lesson, you will learn what fragment shaders are, how to write GLSL code, and how to execute shaders in Flutter using FragmentProgram.

1. What is a Fragment Shader?

In 2D canvas drawing (CustomPainter), your CPU issues vector draw commands (draw lines, draw circles). The GPU rasterizes these shapes.

A Fragment Shader is a specialized mini-program written in GLSL (OpenGL Shading Language) that executes directly on the GPU cores for every single pixel on your canvas simultaneously:

  • If a container is 400x400 pixels, that is 160,000 pixels.
  • The GPU runs your shader on all 160,000 pixels concurrently in parallel!
  • The shader takes input variables (called uniforms—like resolution, time, and touch position) and outputs a final color fragColor for that exact pixel.

2. Writing Your First GLSL Shader (wave.frag)

Create a file named shaders/wave.frag in your project root:

dart
1// shaders/wave.frag
2#include <flutter/runtime_effect.glsl>
3
4// Inputs passed from Flutter (Uniforms)
5uniform vec2 uResolution; // Canvas width and height
6uniform float uTime; // Elapsed animation time
7
8out vec4 fragColor; // Color output for current pixel
9
10void main() {
11 // Normalize pixel coordinates (0.0 to 1.0)
12 vec2 uv = FlutterFragCoord().xy / uResolution;
13
14 // Create an animated sinusoidal wave pattern:
15 float wave = sin(uv.x * 10.0 + uTime * 3.0) * 0.1;
16 float dist = abs(uv.y - 0.5 - wave);
17
18 // Color gradient based on wave distance:
19 vec3 color = vec3(0.1, 0.5, 0.9) * (0.05 / dist);
20
21 fragColor = vec4(color, 1.0);
22}

3. Wiring the Shader into Flutter

  1. Register the shader file in your pubspec.yaml:
flutter:
  shaders:
    - shaders/wave.frag
  1. Load the shader using FragmentProgram.fromAsset() and bind it to a CustomPainter:
dart
1import 'dart:ui' as ui;
2import 'package:flutter/material.dart';
3
4class ShaderScreen extends StatefulWidget {
5 const ShaderScreen({super.key});
6
7 @override
8 State<ShaderScreen> createState() => _ShaderScreenState();
9}
10
11class _ShaderScreenState extends State<ShaderScreen> with SingleTickerProviderStateMixin {
12 ui.FragmentShader? _shader;
13 late final AnimationController _controller;
14
15 @override
16 void initState() {
17 super.initState();
18 _controller = AnimationController(vsync: this, duration: const Duration(seconds: 4))..repeat();
19 _loadShader();
20 }
21
22 Future<void> _loadShader() async {
23 final program = await ui.FragmentProgram.fromAsset('shaders/wave.frag');
24 setState(() => _shader = program.fragmentShader());
25 }
26
27 @override
28 void dispose() {
29 _controller.dispose();
30 _shader?.dispose();
31 super.dispose();
32 }
33
34 @override
35 Widget build(BuildContext context) {
36 if (_shader == null) return const Center(child: CircularProgressIndicator());
37
38 return AnimatedBuilder(
39 animation: _controller,
40 builder: (context, _) => CustomPaint(
41 size: Size.infinite,
42 painter: ShaderPainter(shader: _shader!, time: _controller.value * 6.28),
43 ),
44 );
45 }
46}
47
48class ShaderPainter extends CustomPainter {
49 final ui.FragmentShader shader;
50 final float time;
51
52 ShaderPainter({required this.shader, required this.time});
53
54 @override
55 void paint(Canvas canvas, Size size) {
56 // 1. Pass uniforms in exact order declared in GLSL:
57 shader.setFloat(0, size.width); // uResolution.x
58 shader.setFloat(1, size.height); // uResolution.y
59 shader.setFloat(2, time); // uTime
60
61 // 2. Draw canvas with shader paint:
62 final paint = Paint()..shader = shader;
63 canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), paint);
64 }
65
66 @override
67 bool shouldRepaint(covariant ShaderPainter oldDelegate) => true;
68}

Uniform Index Ordering

💡 Uniform Index Ordering

shader.setFloat(index, value) uses 0-based indices matching the exact sequence of uniform variables defined in the GLSL file. A vec2 consumes 2 slots (index 0 and 1).

Shader Memory Management

⚠️ Shader Memory Management

Always dispose of FragmentShader instances inside your State.dispose() method. Leaving GPU shaders allocated leaks graphics memory buffers.

Impeller Shader Checklist

  • Include <flutter/runtime_effect.glsl> at the top of every .frag shader.
  • Register all shader files under flutter.shaders in pubspec.yaml.
  • Pass canvas dimensions and animation progress via shader.setFloat().
  • Ensure math calculations in GLSL avoid division by zero to prevent black artifacts.
  • Dispose of FragmentShader in State.dispose() to free GPU pipeline resources.

This Lesson In Simple Words

Unlock cinematic visual effects in Flutter using GLSL fragment shaders and Impeller. Animation gives feedback and personality to UI when it supports user intent clearly.

Your level focus

Operate with production and interview-level clarity.

One practical habit

Animate only what helps understanding, and keep transition timing consistent.

Deep Understanding Guide

Why this lesson matters

Good motion guides attention; bad motion distracts and can hurt performance.

Study flow for better retention

  1. Tie each concept to scale, failure handling, and delivery strategy.
  2. Prefer simple implicit animations first, then move to explicit control for complex flows.
  3. If you can defend trade-offs under constraints, your understanding is strong.

Common Mistakes To Avoid

  • Adding animation everywhere without UX purpose.
  • Rebuilding large widget trees for tiny animated changes.
  • Using inconsistent durations that make flows feel random.
  • Ignoring accessibility needs for users sensitive to motion.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Create one implicit and one explicit animation for the same component.
  • Use Hero transition between two screens with meaningful shared element.
  • Profile animation frame times and remove one avoidable rebuild hotspot.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "Where does a Fragment Shader execute in Flutter?".

Code Comprehension Drill

  • State the purpose of the code block in one line before reading details.
  • Mark inputs, state changes, and final output.
  • Change one small value and predict what should happen before running.
  • Run again and compare your prediction with actual behavior.

Architecture Lens

Animation architecture should separate timing logic from reusable visual components.

As your app grows, keep UI, state, and data responsibilities separate so each part stays testable and easier to modify.

Lesson Completion Checklist

  • I can explain "Impeller & Custom GPU Shaders (GLSL)" in simple words without reading notes.
  • I can describe one real app situation where this concept is required.
  • I know at least one mistake to avoid: Adding animation everywhere without UX purpose.
  • I can modify one code sample and correctly predict the behavior change.
  • I can finish required exercises with understanding, not trial-and-error guesses.

Frequently Asked Questions

Where does a Fragment Shader execute in Flutter?

Fragment shaders run massively parallel programs on the GPU for every single pixel on screen.

How do you pass variables (like resolution and time) from Flutter to a GLSL shader?

Inputs in GLSL are called uniforms, and Flutter sets them sequentially using shader.setFloat(index, value).

Which header must be included at the top of a Flutter GLSL shader?

flutter/runtime_effect.glsl provides necessary Flutter coordinate transformations like FlutterFragCoord().

Under which section in pubspec.yaml must custom shader files be declared?

Shaders are compiled at build time by Flutter and must be registered under flutter: shaders: in pubspec.yaml.

Suggest Improvement

Something seems incorrect, unclear, or missing? Let us know.

About The Author

FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.

Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.

Sign in to continue with exercises and quiz for this lesson.

Sign In to Continue