Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create custom TextStyle class on Flutter

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?

like image 741
Aryan V Avatar asked Dec 18 '25 02:12

Aryan V


2 Answers

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,
)
like image 152
Indrajit Sharma Avatar answered Dec 20 '25 15:12

Indrajit Sharma


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),
            ),
          ),
        ),
        [...]
like image 23
Jouby Avatar answered Dec 20 '25 16:12

Jouby



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!