What is LinearGradient? How to use?

LinearGradient is a class in the Flutter framework that creates a linear gradient, which is a gradual blend of two or more colors that create a transition between them in a straight line. It is often used to create background or text effects in Flutter applications.

In this tutorial, we’ll explore the LinearGradient class and learn how to create and use linear gradients in Flutter.

Creating a LinearGradient

How to create Flutter gradient from one color

To create a LinearGradient, you need to define the starting and ending points of the gradient, along with the colors and stops that define the transition between them.

Here’s an example of creating a LinearGradient that goes from blue to green:

LinearGradient myGradient = LinearGradient(
  begin: Alignment.topLeft,
  end: Alignment.bottomRight,
  colors: [Colors.blue, Colors.green],
);

In this example, the begin and end properties define the starting and ending points of the gradient. The colors property is an array of colors that defines the transition between the starting and ending points.

Using a LinearGradient

Once you have created a LinearGradient, you can use it in a variety of ways in your Flutter application. Here are a few examples:

As a background

To use a LinearGradient as a background in a Container, you can set the decoration property to a BoxDecoration that includes the LinearGradient:

Container(
  decoration: BoxDecoration(
    gradient: myGradient,
  ),
  child: ...
)

As text color

To use a LinearGradient as the color of text in a Text widget, you can use a TextSpan with a LinearGradient:

Text.rich(
  TextSpan(
    text: 'Hello',
    style: TextStyle(
      foreground: Paint()..shader = myGradient.createShader(rect),
      fontSize: 32,
    ),
  ),
);

As a foreground

To use a LinearGradient as a foreground, you can use a CustomPaint widget and a Canvas with a drawRect method that includes the LinearGradient:

CustomPaint(
  painter: MyPainter(myGradient),
  child: ...
)
class MyPainter extends CustomPainter {
  final LinearGradient gradient;

  MyPainter(this.gradient);

  @override
  void paint(Canvas canvas, Size size) {
    Rect rect = Offset.zero & size;
    Paint paint = Paint()..shader = gradient.createShader(rect);
    canvas.drawRect(rect, paint);
  }

  @override
  bool shouldRepaint(MyPainter oldDelegate) {
    return false;
  }
}

Conclusion

In this tutorial, we learned how to create and use a LinearGradient in a Flutter application. We saw how to define the starting and ending points of the gradient, along with the colors and stops that define the transition between them. We also explored a few examples of how to use a LinearGradient as a background, text color, and foreground in a Flutter application.

Related posts:

  1. Futter Get started For Beginner
  2. What are Flutter Gestures?
  3. Flutter State Management