Ansh Saini
Posted on January 5, 2023
This is what the official docs say
A list of values from 0.0 to 1.0 that denote fractions along the gradient.
Problem
Lets say we have to create a bar which has a gradient going from red -> green -> blue -> black.
The percentages are as follows:
10% red
30% green
40% blue
Rest of it black (20%)
We might write something like this:
LinearGradient(
colors: [
Colors.red,
Colors.green,
Colors.blue,
Colors.black,
],
stops: [0.1, 0.4, 0.5, 0.2],
),
Here's what we get:
Of course this is not what we want.
How to fix it?
Before we jump into the solution let's look at the problematic code
LinearGradient(
colors: [
Colors.red,
Colors.green,
Colors.blue,
Colors.black,
],
stops: [0.1, 0.4, 0.5, 0.2],
),
We have supplied stops=[0.1, 0.4, 0.5, 0.2]
How the stops
property works
The stops
property requires us to specify where the color should start from. So, if we have two colors, red and black and we want both of them to take 50% of the container, we can write
LinearGradient(
colors: [
Colors.red,
Colors.black,
],
stops: [0, 0.6],
),
Notice that I wrote 0.6
instead of 0.5
. If we write 0.5
, then it would look like a 40-60 split instead of 50-50.
0 to 0.5 would be red, then 0.6 to 1 would be black.
The following code would also give us the same result
LinearGradient(
colors: [
Colors.red,
Colors.black,
],
stops: [0.2, 0.6],
),
This is because as the docs mention, if the stops
array doesn’t start with a 0
, it implicitly means that it would start with 0
and the first color in the colors
array. Same thing happens with last value of stops
array. It should either explicitly end with a 1
, or flutter will implicitly consider it as 1
with last color supplied in the colors
array. So, actually flutter will interpret it as:
LinearGradient(
colors: [
Colors.red,
Colors.red,
Colors.black,
Colors.black,
],
stops: [0, 0.2, 0.6, 1],
),
Fixing the issue
Now that we know how the stops
property works, we can get our desired gradient.
LinearGradient(
colors: [
Colors.red,
Colors.green,
Colors.blue,
Colors.black,
],
stops: [0.1, 0.4, 0.8, 1],
),
Playground
I made a dartpad link if you want to play around with the examples above.
Posted on January 5, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.