Flutter outline text (text stroke)
Published: 2023-10-15 10:00 PM
Flutter outline text
In order to improve character legibility or for design purposes, we can add outlines to text. When there is scaling adjustment or handling of overflow, outlines should also be handled accordingly.
Source code
Github - View the entire source code
import 'package:flutter/material.dart';
class OutlineText extends StatelessWidget {
final Text child;
final double strokeWidth;
final Color? strokeColor;
final TextOverflow? overflow;
const OutlineText(
this.child, {
super.key,
// default storke width
this.strokeWidth = 2,
this.strokeColor,
this.overflow,
});
// Option: can add flags
// e.g.) read a related state and globally apply if needed
// final backgroundProvider = ref.watch(backgroundSelectProvider);
// if (backgroundProvider.imagePath.isEmpty) {
// return child;
// }
Widget build(BuildContext context) {
return Stack(
children: [
// stroke text
Text(
// need to set text scale if needed
textScaleFactor: child.textScaleFactor,
child.data!,
style: TextStyle(
fontSize: child.style?.fontSize,
fontWeight: child.style?.fontWeight,
foreground: Paint()
..color = strokeColor ?? Theme.of(context).shadowColor
..style = PaintingStyle.stroke
..strokeWidth = strokeWidth,
),
// handle overflow
overflow: overflow,
),
// original text
child
],
);
}
}
Examples
...
// basic usage
OutlineText(
Text(
"Hello World!!",
style: Theme.of(context).textTheme.displaySmall,
),
),
// with options
SizedBox(
width: 200,
child: OutlineText(
Text(
"Hello World!! Hello World",
style: Theme.of(context).textTheme.displaySmall,
textScaleFactor: 0.9,
overflow: TextOverflow.ellipsis,
),
strokeWidth: 2,
strokeColor: Colors.amber,
overflow: TextOverflow.ellipsis,
),
)
...