Skip to main content

Flutter Set Gradient Effect on Text - LinearGradient

Foreground property of Text Style is usages the Paint widget to draw effect at the foreground of Text widget. If supports multiple effects and various type of gradient effect. In this tutorial we are drawing linear gradient at the foreground of text widget. There are 5 different type of properties we're using to create gradient effect text in flutter.

Flutter Set Gradient Effect on Text - LinearGradient:

1. Defining Text widget with foreground and applied gradient effect on text.
Text("Sample Text For Flutter",
          style: TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 35,
              foreground: Paint()
                ..shader = const LinearGradient(
                  colors: [
                    Colors.red,
                    Colors.yellow,
                    //add more color here.
                  ],
                ).createShader(const Rect.fromLTWH(100, 100, 200.0, 100.0)))),
Code Explanation:
  • foreground: To draw Paint object at the foreground of the text widget.
  • Paint(): Construct empty paint object for Text.
  • shader: To apply stroke or Fill the shape with desired color.
  • LinearGradient: To create linear gradient.
  • colors: List of colors applied on linear gradient.
  • createShader: Create shader for gradient.
  • Rect.fromLTWH: To construct a rectangle from left and top edges.
2. Complete source code for main.dart file:
import 'package:flutter/material.dart';

void main() {
  runApp(const MaterialApp(home: MyApp()));
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
      child: Text("Sample Text For Flutter",
          style: TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 35,
              foreground: Paint()
                ..shader = const LinearGradient(
                  colors: [
                    Colors.red,
                    Colors.yellow,
                    //add more color here.
                  ],
                ).createShader(const Rect.fromLTWH(100, 100, 200.0, 100.0)))),
    ));
  }
}
Screenshot:
Flutter Set Gradient Effect on Text

Comments