SlideShare a Scribd company logo
1 of 8
Download to read offline
How to Create Custom Shaders in
Flutter?
What are Shaders?
Before creating custom shaders, let’s understand what shaders are!
In Flutter mobile app development, shaders are used to define custom visual effects and
transformations on graphics and UI elements. A shader is a program that runs on the GPU
(Graphics Processing Unit) and controls how each pixel of a rendered image or UI element is
displayed.
Flutter provides the Shader class, which is an abstract base class for different types of shaders.
The most commonly used shaders in Flutter are GradientShader and ImageShader.
Shaders in computer graphics are programs that determine the lighting, darkness, and colour of
objects in a 3D scene. They use GLSL (OpenGL Shading Language) to achieve this. In this blog
post, we’ll explore how to create custom shaders in Flutter using GLSL.
What is GLSL?
GLSL is a programming language used to control the GPU and create custom visual effects and
rendering. It’s similar to C and is specifically designed for real-time environments like video
games and animations.
Let’s create custom shaders!
Now to create a shader in Flutter, we typically write code in GLSL. However, if you prefer to skip
the GLSL coding part, you can choose whatever GLSL code you like and modify it according to
your preference for your Flutter app. There is an online platform called Shadertoy, which allows
users to create and share interactive shaders in GLSL. It provides a playground for
experimenting with real-time graphics and visual effects, making it a popular resource for shader
developers and enthusiasts.
Here, I am using the following code to create my custom shader:
https://www.shadertoy.com/view/ctSSDR
Following code is the original shader from the Shadertoy website.
#define PI 3.1415926535897932384626433832795
voidmainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 center = fragCoord/iResolution.xy – vec2(0.5, 0.5);
floatdist = length(center);
float p = (atan(center.y,center.x)) / (2.0 * PI);
floatnumStripes = 12.0;
boolstripeA = mod(floor((p * numStripes) + (sin(dist * 10.0 + sin(iTime)))), 2.0) == 1.0;
boolstripeB = mod(floor((p * numStripes) – (sin(dist * 10.0 + cos(iTime)))), 2.0) == 1.0;
vec3 col;
if (stripeA&&stripeB)
{
col = vec3(0.4);
}
else if (!stripeA&&stripeB)
{
col = vec3(0.5, 0.2, 0.1);
}
else if (stripeA&& !stripeB)
{
col = vec3(0.3, 0.2, 0.1);
}
else
{
col = vec3(0.7);
}
fragColor = vec4(col,1.0);
}
To get this code to work with Flutter, we have to modify the code as below:
#include <flutter/runtime_effect.glsl>
uniform vec2 uSize;
uniform float iTime;
vec2iResolution;
out vec4 fragColor;
#define PI 3.1415926535897932384626433832795
void main(void) {
iResolution = uSize;
vec2fragCoord = FlutterFragCoord();
// …
// …
}
The changes that we have applied are listed below:
Flutter runtime import is added
#include <flutter/runtime_effect.glsl>
Four new parameters are added
1. uniform vec2 uSize;
2. uniform float iTime;
3. vec2iResolution;
4. out vec4 fragColor;
All the mentioned variables, marked as “uniform”, need to be provided from Flutter when using
the shader program.
The uniform vec2 uSize, which is a constant number provided from Flutter, represents the size
of the item that is being displayed.
The uniform float iTemtracks the elapsed time since the shader started and is utilized to animate
visual effects within the shader.
The vec2 iResolutionholds the screen resolution and is used to adjust the size and position of
the rendered objects.
The out vec4 fragColorserves as the output variable that stores the final color of the rendered
object. This value is subsequently passed back to the CPU for display on the screen.
Atlast, we have added two assignments within the main function
void main(void) {
iResolution = uSize;
vec2fragCoord = FlutterFragCoord();
// …
// …
}
FlutterFragCoord() will be received from the flutter runtime import.
Now, we have to save the full code in a “.frag” file and add it to pubspec.yaml so that we can
utilize it in the flutter. Final code after customizing is as follows :
#include <flutter/runtime_effect.glsl>
uniform vec2 uSize;
uniform float iTime;
vec2iResolution;
out vec4 fragColor;
#define PI 3.1415926535897932384626433832795
void main(void) {
iResolution = uSize;
vec2fragCoord = FlutterFragCoord();
vec2 center = fragCoord/iResolution.xy – vec2(0.5, 0.5);
floatdist = length(center);
float p = (atan(center.y,center.x)) / (2.0 * PI);
floatnumStripes = 12.0;
boolstripeA = mod(floor((p * numStripes) + (sin(dist * 10.0 + sin(iTime)))), 2.0) == 1.0;
boolstripeB = mod(floor((p * numStripes) – (sin(dist * 10.0 + cos(iTime)))), 2.0) == 1.0;
vec3 col;
if (stripeA&&stripeB) {
col = vec3(0.4);
} else if (!stripeA&&stripeB) {
col = vec3(0.5, 0.2, 0.1);
} else if (stripeA&& !stripeB) {
col = vec3(0.3, 0.2, 0.1);
} else {
col = vec3(0.7);
}
fragColor = vec4(col,1.0);
}
Let’s apply the above shader into our flutter application!
Step-1 : To integrate above shader file into our application, we need to add that shader to flutter
pubspec.yaml as mentioned below:
flutter:
shaders:
– shaders/shader.frag
Step-2: Then, we will create a ShaderPainter class which will extend CustomPainter as below:
import ‘dart:ui’;
import ‘package:flutter/material.dart’;
classShaderPainter extends CustomPainter {
finalFragmentShadershader;
final double time;
ShaderPainter(FragmentShaderfragmentShader, this.time)
: shader = fragmentShader;
@override
void paint(Canvas canvas, Size size) {
final paint = Paint();
shader.setFloat(0, size.width);
shader.setFloat(1, size.height);
shader.setFloat(2, time);
paint.shader = shader;
canvas.drawRect(Offset.zero& size, paint);
}
@override
boolshouldRepaint(covariant CustomPainteroldDelegate) => true;
}
Here, we are passing the below variables using setFloat on the FragmentShader:
shader.setFloat(0, size.width);
shader.setFloat(1, size.height);
shader.setFloat(2, time);
Step-3: Now, we will create a StatefulWidget called ShaderHomePage which reads the shader
from the “.frag” file which we created above and passes it to the ShaderPainter as a
FragmentShader.
import ‘dart:async’;
import ‘dart:ui’;
import ‘package:custom_shader_demo/custom_shader.dart’;
import ‘package:flutter/material.dart’;
classShaderHomePage extends StatefulWidget {
constShaderHomePage({super.key});
@override
State<ShaderHomePage>createState() => _ShaderHomePageState();
}
class _ShaderHomePageState extends State<ShaderHomePage> {
late Timer timer;
double delta = 0;
FragmentShader? shader;
voidloadMyShader() async {
var program = await FragmentProgram.fromAsset(‘shaders/shader.frag’);
shader = program.fragmentShader();
setState(() {
// trigger a repaint
});
timer = Timer.periodic(const Duration(milliseconds: 16), (timer) {
setState(() {
delta += 1 / 60;
});
});
}
@override
voidinitState() {
super.initState();
loadMyShader();
}
@override
void dispose() {
timer.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
if (shader == null) {
returnconst Center(child: CircularProgressIndicator());
} else {
returnCustomPaint(painter: ShaderPainter(shader!, delta));
}
}
}
Here, the method which does all the work is loadMyShader.This method reads the shader from
the assets, retrieves the FragmentShader from the FragmentProgram, assigns it to the shader
variable, and also initiates a Timer for potential animation purposes.
late Timer timer;
double delta = 0;
FragmentShader? shader;
voidloadMyShader() async {
var program = await FragmentProgram.fromAsset(‘shaders/shader.frag’);
shader = program.fragmentShader();
setState(() {
// trigger a repaint
});
timer = Timer.periodic(const Duration(milliseconds: 16), (timer) {
setState(() {
delta += 1 / 60;
});
});
}
Output:
Conclusion
A beginner to custom shaders in Flutter should find the material in this description to be a
thorough tutorial that will enable Flutter app developers to comprehend the procedure and begin
building their own custom shaders.
We may also try to convert more complicated glsl code to use, which includes getting a picture
from us and altering it pixel by pixel to produce amazing graphics. This essay simply
demonstrates how to convert very simple glsl code to operate with flutter.

More Related Content

Similar to How to Create Custom Shaders in Flutter?

building_games_with_ruby_rubyconf
building_games_with_ruby_rubyconfbuilding_games_with_ruby_rubyconf
building_games_with_ruby_rubyconftutorialsruby
 
building_games_with_ruby_rubyconf
building_games_with_ruby_rubyconfbuilding_games_with_ruby_rubyconf
building_games_with_ruby_rubyconftutorialsruby
 
HTML5: where flash isn't needed anymore
HTML5: where flash isn't needed anymoreHTML5: where flash isn't needed anymore
HTML5: where flash isn't needed anymoreRemy Sharp
 
Trident International Graphics Workshop 2014 1/5
Trident International Graphics Workshop 2014 1/5Trident International Graphics Workshop 2014 1/5
Trident International Graphics Workshop 2014 1/5Takao Wada
 
Mochi London 2011
Mochi London 2011Mochi London 2011
Mochi London 2011Mike Jones
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDXImplementing a Simple Game using libGDX
Implementing a Simple Game using libGDXJussi Pohjolainen
 
Getting started with Verold and Three.js
Getting started with Verold and Three.jsGetting started with Verold and Three.js
Getting started with Verold and Three.jsVerold
 
Augmented Reality With FlarToolkit and Papervision3D
Augmented Reality With FlarToolkit and Papervision3DAugmented Reality With FlarToolkit and Papervision3D
Augmented Reality With FlarToolkit and Papervision3DRoman Protsyk
 
A 3D printing programming API
A 3D printing programming APIA 3D printing programming API
A 3D printing programming APIMax Kleiner
 
GL Shading Language Document by OpenGL.pdf
GL Shading Language Document by OpenGL.pdfGL Shading Language Document by OpenGL.pdf
GL Shading Language Document by OpenGL.pdfshaikhshehzad024
 
Developer Student Clubs NUK - Flutter for Beginners
Developer Student Clubs NUK - Flutter for BeginnersDeveloper Student Clubs NUK - Flutter for Beginners
Developer Student Clubs NUK - Flutter for BeginnersJiaxuan Lin
 
Android RenderScript
Android RenderScriptAndroid RenderScript
Android RenderScriptJungsoo Nam
 
The Ring programming language version 1.3 book - Part 62 of 88
The Ring programming language version 1.3 book - Part 62 of 88The Ring programming language version 1.3 book - Part 62 of 88
The Ring programming language version 1.3 book - Part 62 of 88Mahmoud Samir Fayed
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best PracticesYekmer Simsek
 
Gdc09 Minigames
Gdc09 MinigamesGdc09 Minigames
Gdc09 MinigamesSusan Gold
 
GDSC Flutter Forward Workshop.pptx
GDSC Flutter Forward Workshop.pptxGDSC Flutter Forward Workshop.pptx
GDSC Flutter Forward Workshop.pptxGDSCVJTI
 
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...Andrey Karpov
 
C Graphics Functions
C Graphics FunctionsC Graphics Functions
C Graphics FunctionsSHAKOOR AB
 
Introduction to Coding
Introduction to CodingIntroduction to Coding
Introduction to CodingFabio506452
 

Similar to How to Create Custom Shaders in Flutter? (20)

building_games_with_ruby_rubyconf
building_games_with_ruby_rubyconfbuilding_games_with_ruby_rubyconf
building_games_with_ruby_rubyconf
 
building_games_with_ruby_rubyconf
building_games_with_ruby_rubyconfbuilding_games_with_ruby_rubyconf
building_games_with_ruby_rubyconf
 
HTML5: where flash isn't needed anymore
HTML5: where flash isn't needed anymoreHTML5: where flash isn't needed anymore
HTML5: where flash isn't needed anymore
 
Trident International Graphics Workshop 2014 1/5
Trident International Graphics Workshop 2014 1/5Trident International Graphics Workshop 2014 1/5
Trident International Graphics Workshop 2014 1/5
 
Mochi London 2011
Mochi London 2011Mochi London 2011
Mochi London 2011
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDXImplementing a Simple Game using libGDX
Implementing a Simple Game using libGDX
 
Getting started with Verold and Three.js
Getting started with Verold and Three.jsGetting started with Verold and Three.js
Getting started with Verold and Three.js
 
20151224-games
20151224-games20151224-games
20151224-games
 
Augmented Reality With FlarToolkit and Papervision3D
Augmented Reality With FlarToolkit and Papervision3DAugmented Reality With FlarToolkit and Papervision3D
Augmented Reality With FlarToolkit and Papervision3D
 
A 3D printing programming API
A 3D printing programming APIA 3D printing programming API
A 3D printing programming API
 
GL Shading Language Document by OpenGL.pdf
GL Shading Language Document by OpenGL.pdfGL Shading Language Document by OpenGL.pdf
GL Shading Language Document by OpenGL.pdf
 
Developer Student Clubs NUK - Flutter for Beginners
Developer Student Clubs NUK - Flutter for BeginnersDeveloper Student Clubs NUK - Flutter for Beginners
Developer Student Clubs NUK - Flutter for Beginners
 
Android RenderScript
Android RenderScriptAndroid RenderScript
Android RenderScript
 
The Ring programming language version 1.3 book - Part 62 of 88
The Ring programming language version 1.3 book - Part 62 of 88The Ring programming language version 1.3 book - Part 62 of 88
The Ring programming language version 1.3 book - Part 62 of 88
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
 
Gdc09 Minigames
Gdc09 MinigamesGdc09 Minigames
Gdc09 Minigames
 
GDSC Flutter Forward Workshop.pptx
GDSC Flutter Forward Workshop.pptxGDSC Flutter Forward Workshop.pptx
GDSC Flutter Forward Workshop.pptx
 
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
 
C Graphics Functions
C Graphics FunctionsC Graphics Functions
C Graphics Functions
 
Introduction to Coding
Introduction to CodingIntroduction to Coding
Introduction to Coding
 

More from Flutter Agency

User Enhancement With Animated Flutter Drawer
User Enhancement With Animated Flutter DrawerUser Enhancement With Animated Flutter Drawer
User Enhancement With Animated Flutter DrawerFlutter Agency
 
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosUnit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosFlutter Agency
 
Form Validation in Flutter with Laravel Form Validation Syntax
Form Validation in Flutter with Laravel Form Validation SyntaxForm Validation in Flutter with Laravel Form Validation Syntax
Form Validation in Flutter with Laravel Form Validation SyntaxFlutter Agency
 
Benefits Of Hiring Flutter App Developers For Success
Benefits Of Hiring Flutter App Developers For SuccessBenefits Of Hiring Flutter App Developers For Success
Benefits Of Hiring Flutter App Developers For SuccessFlutter Agency
 
Guide to Fix Dropdown Button Not Switching Selected Item | Flutter
Guide to Fix Dropdown Button Not Switching Selected Item | FlutterGuide to Fix Dropdown Button Not Switching Selected Item | Flutter
Guide to Fix Dropdown Button Not Switching Selected Item | FlutterFlutter Agency
 
12 Straightforward Steps to Build Your Video On-Demand App in 2024
12 Straightforward Steps to Build Your Video On-Demand App in 202412 Straightforward Steps to Build Your Video On-Demand App in 2024
12 Straightforward Steps to Build Your Video On-Demand App in 2024Flutter Agency
 
Flutter's Advantages For Custom Application Development Services
Flutter's Advantages For Custom Application Development ServicesFlutter's Advantages For Custom Application Development Services
Flutter's Advantages For Custom Application Development ServicesFlutter Agency
 
Hire Flutter Developers to Build Cross-Platform App Services - Stonesmentor
Hire Flutter Developers to Build Cross-Platform App Services - StonesmentorHire Flutter Developers to Build Cross-Platform App Services - Stonesmentor
Hire Flutter Developers to Build Cross-Platform App Services - StonesmentorFlutter Agency
 
A Guide For Recovering Your Failing App Project | Flutter Agency
A Guide For Recovering Your Failing App Project | Flutter AgencyA Guide For Recovering Your Failing App Project | Flutter Agency
A Guide For Recovering Your Failing App Project | Flutter AgencyFlutter Agency
 
Healthcare App-Development Company Fllutter Agency
Healthcare App-Development Company Fllutter AgencyHealthcare App-Development Company Fllutter Agency
Healthcare App-Development Company Fllutter AgencyFlutter Agency
 
Is Flutter Good for Web Development? | Flutter Agency
Is Flutter Good for Web Development? | Flutter AgencyIs Flutter Good for Web Development? | Flutter Agency
Is Flutter Good for Web Development? | Flutter AgencyFlutter Agency
 
Choosing App Development: Native, Hybrid, or Flutter Explained
Choosing App Development: Native, Hybrid, or Flutter ExplainedChoosing App Development: Native, Hybrid, or Flutter Explained
Choosing App Development: Native, Hybrid, or Flutter ExplainedFlutter Agency
 
The Role of Digital Transformation in Healthcare - Flutter Agency.pdf
The Role of Digital Transformation in Healthcare - Flutter Agency.pdfThe Role of Digital Transformation in Healthcare - Flutter Agency.pdf
The Role of Digital Transformation in Healthcare - Flutter Agency.pdfFlutter Agency
 
Why-Hire-Flutter-Developer-Flutter-Agency_.pdf
Why-Hire-Flutter-Developer-Flutter-Agency_.pdfWhy-Hire-Flutter-Developer-Flutter-Agency_.pdf
Why-Hire-Flutter-Developer-Flutter-Agency_.pdfFlutter Agency
 
Streamlining DNS Checks in Flutter Apps
Streamlining DNS Checks in Flutter AppsStreamlining DNS Checks in Flutter Apps
Streamlining DNS Checks in Flutter AppsFlutter Agency
 
Flutter UI/UX Design Tools: The Ultimate Guide for 2023
Flutter UI/UX Design Tools: The Ultimate Guide for 2023Flutter UI/UX Design Tools: The Ultimate Guide for 2023
Flutter UI/UX Design Tools: The Ultimate Guide for 2023Flutter Agency
 
Flutter Developer Skills to Master in 2024.pdf
Flutter Developer Skills to Master in 2024.pdfFlutter Developer Skills to Master in 2024.pdf
Flutter Developer Skills to Master in 2024.pdfFlutter Agency
 
Circular Timer in Flutter.pdf
Circular Timer in Flutter.pdfCircular Timer in Flutter.pdf
Circular Timer in Flutter.pdfFlutter Agency
 
flutteragency-com-handling-events-and-user-input-in-flutter-.pdf
flutteragency-com-handling-events-and-user-input-in-flutter-.pdfflutteragency-com-handling-events-and-user-input-in-flutter-.pdf
flutteragency-com-handling-events-and-user-input-in-flutter-.pdfFlutter Agency
 
Best Flutter Application Development Tools in 2022.pptx
Best Flutter Application Development Tools in 2022.pptxBest Flutter Application Development Tools in 2022.pptx
Best Flutter Application Development Tools in 2022.pptxFlutter Agency
 

More from Flutter Agency (20)

User Enhancement With Animated Flutter Drawer
User Enhancement With Animated Flutter DrawerUser Enhancement With Animated Flutter Drawer
User Enhancement With Animated Flutter Drawer
 
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosUnit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
 
Form Validation in Flutter with Laravel Form Validation Syntax
Form Validation in Flutter with Laravel Form Validation SyntaxForm Validation in Flutter with Laravel Form Validation Syntax
Form Validation in Flutter with Laravel Form Validation Syntax
 
Benefits Of Hiring Flutter App Developers For Success
Benefits Of Hiring Flutter App Developers For SuccessBenefits Of Hiring Flutter App Developers For Success
Benefits Of Hiring Flutter App Developers For Success
 
Guide to Fix Dropdown Button Not Switching Selected Item | Flutter
Guide to Fix Dropdown Button Not Switching Selected Item | FlutterGuide to Fix Dropdown Button Not Switching Selected Item | Flutter
Guide to Fix Dropdown Button Not Switching Selected Item | Flutter
 
12 Straightforward Steps to Build Your Video On-Demand App in 2024
12 Straightforward Steps to Build Your Video On-Demand App in 202412 Straightforward Steps to Build Your Video On-Demand App in 2024
12 Straightforward Steps to Build Your Video On-Demand App in 2024
 
Flutter's Advantages For Custom Application Development Services
Flutter's Advantages For Custom Application Development ServicesFlutter's Advantages For Custom Application Development Services
Flutter's Advantages For Custom Application Development Services
 
Hire Flutter Developers to Build Cross-Platform App Services - Stonesmentor
Hire Flutter Developers to Build Cross-Platform App Services - StonesmentorHire Flutter Developers to Build Cross-Platform App Services - Stonesmentor
Hire Flutter Developers to Build Cross-Platform App Services - Stonesmentor
 
A Guide For Recovering Your Failing App Project | Flutter Agency
A Guide For Recovering Your Failing App Project | Flutter AgencyA Guide For Recovering Your Failing App Project | Flutter Agency
A Guide For Recovering Your Failing App Project | Flutter Agency
 
Healthcare App-Development Company Fllutter Agency
Healthcare App-Development Company Fllutter AgencyHealthcare App-Development Company Fllutter Agency
Healthcare App-Development Company Fllutter Agency
 
Is Flutter Good for Web Development? | Flutter Agency
Is Flutter Good for Web Development? | Flutter AgencyIs Flutter Good for Web Development? | Flutter Agency
Is Flutter Good for Web Development? | Flutter Agency
 
Choosing App Development: Native, Hybrid, or Flutter Explained
Choosing App Development: Native, Hybrid, or Flutter ExplainedChoosing App Development: Native, Hybrid, or Flutter Explained
Choosing App Development: Native, Hybrid, or Flutter Explained
 
The Role of Digital Transformation in Healthcare - Flutter Agency.pdf
The Role of Digital Transformation in Healthcare - Flutter Agency.pdfThe Role of Digital Transformation in Healthcare - Flutter Agency.pdf
The Role of Digital Transformation in Healthcare - Flutter Agency.pdf
 
Why-Hire-Flutter-Developer-Flutter-Agency_.pdf
Why-Hire-Flutter-Developer-Flutter-Agency_.pdfWhy-Hire-Flutter-Developer-Flutter-Agency_.pdf
Why-Hire-Flutter-Developer-Flutter-Agency_.pdf
 
Streamlining DNS Checks in Flutter Apps
Streamlining DNS Checks in Flutter AppsStreamlining DNS Checks in Flutter Apps
Streamlining DNS Checks in Flutter Apps
 
Flutter UI/UX Design Tools: The Ultimate Guide for 2023
Flutter UI/UX Design Tools: The Ultimate Guide for 2023Flutter UI/UX Design Tools: The Ultimate Guide for 2023
Flutter UI/UX Design Tools: The Ultimate Guide for 2023
 
Flutter Developer Skills to Master in 2024.pdf
Flutter Developer Skills to Master in 2024.pdfFlutter Developer Skills to Master in 2024.pdf
Flutter Developer Skills to Master in 2024.pdf
 
Circular Timer in Flutter.pdf
Circular Timer in Flutter.pdfCircular Timer in Flutter.pdf
Circular Timer in Flutter.pdf
 
flutteragency-com-handling-events-and-user-input-in-flutter-.pdf
flutteragency-com-handling-events-and-user-input-in-flutter-.pdfflutteragency-com-handling-events-and-user-input-in-flutter-.pdf
flutteragency-com-handling-events-and-user-input-in-flutter-.pdf
 
Best Flutter Application Development Tools in 2022.pptx
Best Flutter Application Development Tools in 2022.pptxBest Flutter Application Development Tools in 2022.pptx
Best Flutter Application Development Tools in 2022.pptx
 

Recently uploaded

Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutionsmonugehlot87
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 

Recently uploaded (20)

Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutions
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 

How to Create Custom Shaders in Flutter?

  • 1. How to Create Custom Shaders in Flutter? What are Shaders? Before creating custom shaders, let’s understand what shaders are! In Flutter mobile app development, shaders are used to define custom visual effects and transformations on graphics and UI elements. A shader is a program that runs on the GPU (Graphics Processing Unit) and controls how each pixel of a rendered image or UI element is displayed. Flutter provides the Shader class, which is an abstract base class for different types of shaders. The most commonly used shaders in Flutter are GradientShader and ImageShader. Shaders in computer graphics are programs that determine the lighting, darkness, and colour of objects in a 3D scene. They use GLSL (OpenGL Shading Language) to achieve this. In this blog post, we’ll explore how to create custom shaders in Flutter using GLSL.
  • 2. What is GLSL? GLSL is a programming language used to control the GPU and create custom visual effects and rendering. It’s similar to C and is specifically designed for real-time environments like video games and animations. Let’s create custom shaders! Now to create a shader in Flutter, we typically write code in GLSL. However, if you prefer to skip the GLSL coding part, you can choose whatever GLSL code you like and modify it according to your preference for your Flutter app. There is an online platform called Shadertoy, which allows users to create and share interactive shaders in GLSL. It provides a playground for experimenting with real-time graphics and visual effects, making it a popular resource for shader developers and enthusiasts. Here, I am using the following code to create my custom shader: https://www.shadertoy.com/view/ctSSDR Following code is the original shader from the Shadertoy website. #define PI 3.1415926535897932384626433832795 voidmainImage( out vec4 fragColor, in vec2 fragCoord ) { vec2 center = fragCoord/iResolution.xy – vec2(0.5, 0.5); floatdist = length(center); float p = (atan(center.y,center.x)) / (2.0 * PI); floatnumStripes = 12.0; boolstripeA = mod(floor((p * numStripes) + (sin(dist * 10.0 + sin(iTime)))), 2.0) == 1.0; boolstripeB = mod(floor((p * numStripes) – (sin(dist * 10.0 + cos(iTime)))), 2.0) == 1.0; vec3 col; if (stripeA&&stripeB) { col = vec3(0.4); } else if (!stripeA&&stripeB) { col = vec3(0.5, 0.2, 0.1); } else if (stripeA&& !stripeB) { col = vec3(0.3, 0.2, 0.1); } else { col = vec3(0.7);
  • 3. } fragColor = vec4(col,1.0); } To get this code to work with Flutter, we have to modify the code as below: #include <flutter/runtime_effect.glsl> uniform vec2 uSize; uniform float iTime; vec2iResolution; out vec4 fragColor; #define PI 3.1415926535897932384626433832795 void main(void) { iResolution = uSize; vec2fragCoord = FlutterFragCoord(); // … // … } The changes that we have applied are listed below: Flutter runtime import is added #include <flutter/runtime_effect.glsl> Four new parameters are added 1. uniform vec2 uSize; 2. uniform float iTime; 3. vec2iResolution; 4. out vec4 fragColor; All the mentioned variables, marked as “uniform”, need to be provided from Flutter when using the shader program. The uniform vec2 uSize, which is a constant number provided from Flutter, represents the size of the item that is being displayed. The uniform float iTemtracks the elapsed time since the shader started and is utilized to animate visual effects within the shader. The vec2 iResolutionholds the screen resolution and is used to adjust the size and position of the rendered objects. The out vec4 fragColorserves as the output variable that stores the final color of the rendered object. This value is subsequently passed back to the CPU for display on the screen.
  • 4. Atlast, we have added two assignments within the main function void main(void) { iResolution = uSize; vec2fragCoord = FlutterFragCoord(); // … // … } FlutterFragCoord() will be received from the flutter runtime import. Now, we have to save the full code in a “.frag” file and add it to pubspec.yaml so that we can utilize it in the flutter. Final code after customizing is as follows : #include <flutter/runtime_effect.glsl> uniform vec2 uSize; uniform float iTime; vec2iResolution; out vec4 fragColor; #define PI 3.1415926535897932384626433832795 void main(void) { iResolution = uSize; vec2fragCoord = FlutterFragCoord(); vec2 center = fragCoord/iResolution.xy – vec2(0.5, 0.5); floatdist = length(center); float p = (atan(center.y,center.x)) / (2.0 * PI); floatnumStripes = 12.0; boolstripeA = mod(floor((p * numStripes) + (sin(dist * 10.0 + sin(iTime)))), 2.0) == 1.0; boolstripeB = mod(floor((p * numStripes) – (sin(dist * 10.0 + cos(iTime)))), 2.0) == 1.0; vec3 col; if (stripeA&&stripeB) { col = vec3(0.4); } else if (!stripeA&&stripeB) { col = vec3(0.5, 0.2, 0.1); } else if (stripeA&& !stripeB) { col = vec3(0.3, 0.2, 0.1); } else { col = vec3(0.7); } fragColor = vec4(col,1.0); }
  • 5. Let’s apply the above shader into our flutter application! Step-1 : To integrate above shader file into our application, we need to add that shader to flutter pubspec.yaml as mentioned below: flutter: shaders: – shaders/shader.frag Step-2: Then, we will create a ShaderPainter class which will extend CustomPainter as below: import ‘dart:ui’; import ‘package:flutter/material.dart’; classShaderPainter extends CustomPainter { finalFragmentShadershader; final double time; ShaderPainter(FragmentShaderfragmentShader, this.time) : shader = fragmentShader; @override void paint(Canvas canvas, Size size) { final paint = Paint(); shader.setFloat(0, size.width); shader.setFloat(1, size.height); shader.setFloat(2, time); paint.shader = shader; canvas.drawRect(Offset.zero& size, paint); } @override boolshouldRepaint(covariant CustomPainteroldDelegate) => true; } Here, we are passing the below variables using setFloat on the FragmentShader: shader.setFloat(0, size.width); shader.setFloat(1, size.height); shader.setFloat(2, time); Step-3: Now, we will create a StatefulWidget called ShaderHomePage which reads the shader from the “.frag” file which we created above and passes it to the ShaderPainter as a FragmentShader. import ‘dart:async’; import ‘dart:ui’; import ‘package:custom_shader_demo/custom_shader.dart’;
  • 6. import ‘package:flutter/material.dart’; classShaderHomePage extends StatefulWidget { constShaderHomePage({super.key}); @override State<ShaderHomePage>createState() => _ShaderHomePageState(); } class _ShaderHomePageState extends State<ShaderHomePage> { late Timer timer; double delta = 0; FragmentShader? shader; voidloadMyShader() async { var program = await FragmentProgram.fromAsset(‘shaders/shader.frag’); shader = program.fragmentShader(); setState(() { // trigger a repaint }); timer = Timer.periodic(const Duration(milliseconds: 16), (timer) { setState(() { delta += 1 / 60; }); }); } @override voidinitState() { super.initState(); loadMyShader(); } @override void dispose() { timer.cancel(); super.dispose(); } @override Widget build(BuildContext context) { if (shader == null) { returnconst Center(child: CircularProgressIndicator()); } else { returnCustomPaint(painter: ShaderPainter(shader!, delta)); } } }
  • 7. Here, the method which does all the work is loadMyShader.This method reads the shader from the assets, retrieves the FragmentShader from the FragmentProgram, assigns it to the shader variable, and also initiates a Timer for potential animation purposes. late Timer timer; double delta = 0; FragmentShader? shader; voidloadMyShader() async { var program = await FragmentProgram.fromAsset(‘shaders/shader.frag’); shader = program.fragmentShader(); setState(() { // trigger a repaint }); timer = Timer.periodic(const Duration(milliseconds: 16), (timer) { setState(() { delta += 1 / 60; }); }); } Output:
  • 8. Conclusion A beginner to custom shaders in Flutter should find the material in this description to be a thorough tutorial that will enable Flutter app developers to comprehend the procedure and begin building their own custom shaders. We may also try to convert more complicated glsl code to use, which includes getting a picture from us and altering it pixel by pixel to produce amazing graphics. This essay simply demonstrates how to convert very simple glsl code to operate with flutter.