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.
-
3pub.dartlang.org/packages/gradient_widgets– Shyju MNov 29, 2018 at 9:29
-
1Take look at ShaderMask. Probably it is most simple solution api.flutter.dev/flutter/widgets/ShaderMask-class.html– Vladimir BerezkinJul 29, 2019 at 6:47
-
check this link bestflutterpack.com/how-to-display-gradient-text-in-flutter– Jishnu ChandranJul 16, 2021 at 5:33
4 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,
]),
),
Live Demo
-
-
great and functional answer, thanks friend. but on the web, I'm having some problems to that effect. Sep 18, 2022 at 0:40
-
I had a better result with "BlendMode.dstIn" rather than "BlendMode.srcIn", but the overall solution works well, thanks! Oct 9, 2022 at 18:25
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),
)
Use simple_gradient_text package and create GradienText
GradientText(
'Gradient Text Example',
style: TextStyle(
fontSize: 40.0,
),
colors: [
Colors.blue,
Colors.red,
Colors.teal,
],
),
First, we import Pkg
Radial gradient
GradientText(
'Gradient Text Example',
style: TextStyle(
fontSize: 40.0,
),
gradientType: GradientType.radial,
gradientDirection: GradientDirection.ttb,
radius: 6,
colors: [
Color(0xff159DFF),
Color(0xff002981),
],
),
Linear gradient
GradientText(
'Gradient Text Example',
style: TextStyle(
fontSize: 40.0,
),
gradientType: GradientType.linear,
gradientDirection: GradientDirection.ttb,
radius: .4,
colors: [
Color(0xff159DFF),
Color(0xff002981),
],
),