Flutter How to Apply Shader Mask to a Background Image
i was creating a login screen for an app. I used a PNG image as the background. i wanted to darken the entire image with half opacity and have full black color at the bottom of the screen where login button and register buttons are placed.
let me walk you through the Full process
first create a container
add a decoration
property assign BoxDecoration
widget to it. inside the BoxDecoration
widget add your background image as a decoration image.to make the image occupy entire screen add fit: Boxfit.Cover
and then to make the image darker add colorfilter
property and ColorFilter
widget with darken as BlendMode
.
The code will produce a result like this
Add ShaderMask
once you have the background image setup, wrap Container
with ShaderMask
widget shadermask widget needs shaderCallback
property with a function. the function will must have a parameter you can give any name for the parameter i am giving rect
.
Inside that function add LinerGradient
widget. to use LinerGradient you must specify these properties begin,end,colors
begin and end is for specifying gradients position and colors property is a list of colors for gradient to use.
now we need return the gradient as a shader to do that at the end of the LinerGradient add createShader(rect)
function notice that it has rect as parameter. the create shader function parameter and shadercallback function parameter must be the same for the code to run.
Here is the final code
Result: