How to create a global TextStyle in Flutter?

6.1k Views Asked by At

In my home page in build widget before return statement I use below code. If I create an another widget in my home page I have to copy below code before each return statement. If you create another stateless/stateful dart file I need to copy below code again.

My question is How to create a global TextStyle in Flutter? I don't want to change Theme data, all want to use my TextStyle across the my flutter project. Thanks.

  TextStyle myNormalStyle = TextStyle(
        fontSize: SizerUtil.deviceType == DeviceType.Mobile ? 14.0.sp : 13.0.sp,
        fontStyle: FontStyle.normal,
        fontWeight: FontWeight.normal,
        color: Colors.black);
2

There are 2 best solutions below

0
On BEST ANSWER

You can easily you that using by using Theme. As described on the flutter docs you can use it like :

MaterialApp(
  title: title,
  theme: ThemeData(
    // Define the default brightness and colors.
    brightness: Brightness.dark,
    primaryColor: Colors.lightBlue[800],
    accentColor: Colors.cyan[600],

    // Define the default font family.
    fontFamily: 'Georgia',

    // Define the default TextTheme. Use this to specify the default
    // text styling for headlines, titles, bodies of text, and more.
    textTheme: TextTheme(
      headline1: TextStyle(fontSize: 72.0, fontWeight: FontWeight.bold),
      headline6: TextStyle(fontSize: 36.0, fontStyle: FontStyle.italic),
      bodyText2: TextStyle(fontSize: 14.0, fontFamily: 'Hind'),
    ),
  )
);

or you can also use DefaultTextStyle widget to provide a default TextStyle to all the children of this widget. Read more about DefaultTextStyle.

1
On

1º create a class file:

import 'package:flutter/material.dart';
class MyTextStyle {
  static const TextStyle textStyle = TextStyle(
    color: Color.fromARGB(255, 247, 240, 201),
    fontSize: 20,
    fontWeight: FontWeight.bold,
  ); 
}

2º import and use in your screen:

import 'package:MyApp/MyTextStyle.dart';
    const Text(
              'You have pushed the button this many times:',
              style: MyTextStyle.textStyle,
    ),