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.
You can use ShaderMask
for that. Remember to set the Text
's color to white and you're good
import 'package:flutter/material.dart';
class GradientText extends StatelessWidget {
GradientText(
this.text, {
@required this.gradient,
});
final String text;
final Gradient gradient;
@override
Widget build(BuildContext context) {
return ShaderMask(
shaderCallback: (bounds) => gradient.createShader(
Rect.fromLTWH(0, 0, bounds.width, bounds.height),
),
child: Text(
text,
style: TextStyle(
// The color must be set to white for this to work
color: Colors.white,
fontSize: 40,
),
),
);
}
}
class GradientTextWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: SizedBox.expand(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
GradientText(
'Hello Flutter',
gradient: LinearGradient(colors: [
Colors.blue.shade400,
Colors.blue.shade900,
]),
),
GradientText(
'Rainbow',
gradient: LinearGradient(colors: [
Colors.red,
Colors.pink,
Colors.purple,
Colors.deepPurple,
Colors.deepPurple,
Colors.indigo,
Colors.blue,
Colors.lightBlue,
Colors.cyan,
Colors.teal,
Colors.green,
Colors.lightGreen,
Colors.lime,
Colors.yellow,
Colors.amber,
Colors.orange,
Colors.deepOrange,
]),
),
GradientText(
'Fade out',
gradient: LinearGradient(
colors: [
Colors.black,
Colors.white,
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
),
],
),
),
);
}
}