Reputation: 22417
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.
Upvotes: 48
Views: 61627
Reputation: 320
First, we import Pkg
GradientText(
'Gradient Text Example',
style: TextStyle(
fontSize: 40.0,
),
gradientType: GradientType.radial,
gradientDirection: GradientDirection.ttb,
radius: 6,
colors: [
Color(0xff159DFF),
Color(0xff002981),
],
),
GradientText(
'Gradient Text Example',
style: TextStyle(
fontSize: 40.0,
),
gradientType: GradientType.linear,
gradientDirection: GradientDirection.ttb,
radius: .4,
colors: [
Color(0xff159DFF),
Color(0xff002981),
],
),
Upvotes: 2
Reputation: 81400
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),
);
}
}
GradientText(
'Hello Flutter',
style: const TextStyle(fontSize: 40),
gradient: LinearGradient(colors: [
Colors.blue.shade400,
Colors.blue.shade900,
]),
),
Upvotes: 136
Reputation: 379
Use simple_gradient_text package and create GradienText
GradientText(
'Gradient Text Example',
style: TextStyle(
fontSize: 40.0,
),
colors: [
Colors.blue,
Colors.red,
Colors.teal,
],
),
Upvotes: 10
Reputation: 22417
Taken from here, you can use Text's style painter.
Create the shader,
final Shader linearGradient = LinearGradient(
colors: <Color>[Color(0xffDA44bb), Color(0xff8921aa)],
).createShader(Rect.fromLTWH(0.0, 0.0, 200.0, 70.0));
then use it in the TextStyle's foreground
Text(
'Hello Gradients!',
style: new TextStyle(
fontSize: 60.0,
fontWeight: FontWeight.bold,
foreground: Paint()..shader = linearGradient),
)
Upvotes: 73