How can I create a custom TextStyle class in flutter? For example I have several buttons and want the text inside to all be the same fontSize and color but I don't want to repeat the TextStyle inside of each Text widget, but instead create something such as CustomTextStyle that I could use in the place of the TextStyle itself. Is there a way to do this?
Create a separate class names CustomTextStyle and add the styles inside them like:
class CustomTextStyle {
static const TextStyle nameOfTextStyle = TextStyle(
fontSize: 24,
color: Colors.green,
fontWeight: FontWeight.bold,
);
}
Now you can use it in Text widget like:
Text('Lorem Ipsum',
style: CustomTextStyle.nameOfTextStyle,
)
To define your button or text style globally, you need to use theme.
For example, you can define a custom theme for TextButton :
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
textButtonTheme: TextButtonThemeData(
style: ButtonStyle(
textStyle: MaterialStateProperty.all(
const TextStyle(fontSize: 20),
),
),
),
[...]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With