This repository contains a demo application showcasing the integration of fragment shaders in Flutter.
Flutter.Fragment.Shaders.Demo.mov
Like this project? Consider supporting its upkeep with a coffee. Your generosity is appreciated! ☕
Fragment shaders are a type of shader used in 3D graphics for shading pixels. They can be used to create stunning visual effects and manipulate pixels in real-time applications.
To use custom shaders in your Flutter project, you need to add them to your pubspec.yaml file. Here’s how you can do it:
-
Create the Shader File: Write your shader program in a file with a
.frag
extension. This file contains the GLSL code for your custom shader. -
Add the Shader to
pubspec.yaml
: In yourpubspec.yaml
file, you need to add ashaders
section under theflutter
section. Here, you list all the shader files (with their paths) that you want to include in your project. For example:
flutter:
shaders:
- shaders/myshader.frag
In this example, myshader.frag
is the shader file located in the /shaders
directory of your project
- Create a Custom Painter: In your Dart code, create a custom painter that extends
CustomPainter
. This custom painter will use the shader when painting.
Here are some examples of how to use fragment shaders in your Flutter project:
- Loading the Shader: To load a shader into a
FragmentProgram
object at runtime, use theFragmentProgram.fromAsset
constructor. The asset’s name is the same as the path to the shader given in thepubspec.yaml
file. TheFragmentProgram
object can then be used to create one or moreFragmentShader
instances. - Using the FragmentShader: A
FragmentShader
object represents a fragment program along with a particular set of uniforms (configuration parameters). The available uniforms depend on how the shader was defined. In this example, I'm using thesetFloat
method on myFragmentShader
instance to set these uniforms.
For more information on writing and using fragment shaders in Flutter, check out the Flutter documentation on fragment shaders.
The shaders used in this demo were not written by me. They were authored by the following individuals:
- Galaxy: Authored by Dave Hoskins
- Fire Heart: Authored by lz
- Fire: Authored by Shane
- Heartbeat: Authored by mushroom
All credit for the shader code goes to them.