Change color of text in flutter
April 26, 2023 . 6 min read
In this example, I'm going to show you how you can change the color of your text in flutter, add shadow to it, or give a color gradient to it. With flutter's TextStyle() constructor, we can style our text according to our design requirements.
Let's give some color to text:
TexStyle() constructor contains:
TextStyle({
bool inherit = true,
Color? color,
Color? backgroundColor,
double? fontSize,
FontWeight? fontWeight,
FontStyle? fontStyle,
double? letterSpacing,
double? wordSpacing,
TextBaseline? textBaseline,
double? height,
TextLeadingDistribution? leadingDistribution,
Locale? locale,
Paint? foreground,
Paint? background,
List<Shadow>? shadows,
List<FontFeature>? fontFeatures,
List<FontVariation>? fontVariations,
TextDecoration? decoration,
Color? decorationColor,
TextDecorationStyle? decorationStyle,
double? decorationThickness,
String? debugLabel,
String? fontFamily,
List<String>? fontFamilyFallback,
String? package,
TextOverflow? overflow, })
To give color to text pass TextStyle() constructor to the named argument "style" of Text() constructor.
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Flutter change color of text"),
),
body: Center(
child: Text(
'Flutteradda.com',
style: TextStyle(
fontSize: 20,
color: Colors.red
),
),
)
);
}
Borders and Stroke(Foreground of a text)
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Flutter change color of text"),
),
body: Center(
child: Text(
'Flutteradda.com',
style: TextStyle(
fontSize: 40,
foreground: Paint()
..style = PaintingStyle.stroke
..strokeWidth = 4
..color = Colors.red[600]!,
),
),
)
);
}
Gradient(Foreground of a text)
To apply gradient to a text add this import statement:
import 'dart:ui' as ui;
and then add the following code in the TextStyle() as given below.
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Flutter change color of text"),
),
body: Center(
child: Text(
'Flutteradda.com',
style: TextStyle(
fontSize: 40,
foreground: Paint()
..shader = ui.Gradient.linear(
const Offset(0, 20),
const Offset(150, 20),
<Color>[
Colors.blueAccent,
Colors.orange,
],
)
),
),
)
);
}
To Learn more about TextStyle() please follow this link: TextStyle() in Flutter