Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gradient Text in Flutter

I was wondering if it is possible to create a gradient over text Flutter. There is a gist of text gradient using Dart's ui, but it is kinda long and I was hoping to be simpler.

like image 533
AbdulMomen عبدالمؤمن Avatar asked Aug 04 '18 15:08

AbdulMomen عبدالمؤمن


People also ask

How do you give a gradient a color in text in Flutter?

Using a shader for Gradient textfinal Shader linearGradient = LinearGradient( colors: <Color>[Colors. pink, Colors. green], ). createShader( Rect.

How do you change text color on Flutter?

Steps. Step 1: Locate the file where you have placed the Text widget. Step 2: Inside the Text widget, add the Style parameter and assign the TextStyle widget. Step 3: Inside the TextStyle widget, add the color parameter and set the color of your choice.


1 Answers

You can use ShaderMask for that task. In ShaderMask, you need to set the BlendMode to BlendMode.srcIn, "src" means the widget to apply the gradient to (in this case Text), "in" means only show the part of the Text where it overlaps with the background which is the text itself (so the gradient doesn't get applied on the background):

import 'package:flutter/material.dart';

class GradientText extends StatelessWidget {
  const GradientText(
    this.text, {
    required this.gradient,
    this.style,
  });

  final String text;
  final TextStyle? style;
  final Gradient gradient;

  @override
  Widget build(BuildContext context) {
    return ShaderMask(
      blendMode: BlendMode.srcIn,
      shaderCallback: (bounds) => gradient.createShader(
        Rect.fromLTWH(0, 0, bounds.width, bounds.height),
      ),
      child: Text(text, style: style),
    );
  }
}

Usage

GradientText(
  'Hello Flutter',
  style: const TextStyle(fontSize: 40),
  gradient: LinearGradient(colors: [
    Colors.blue.shade400,
    Colors.blue.shade900,
  ]),
),

enter image description here

Live Demo

like image 86
NearHuscarl Avatar answered Oct 03 '22 19:10

NearHuscarl