Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define custom text theme in flutter?

Tags:

flutter

How to make my own text theme style? I only find the default text theme like this but it's not enough.

textTheme: TextTheme(
  body1: TextStyle(),
  body2: TextStyle(),
  button: TextStyle(),
  caption: TextStyle(),
  display1: TextStyle(),
  display2: TextStyle(),
  display3: TextStyle(),
  display4: TextStyle(),
  headline: TextStyle(),
  overline: TextStyle(),
  subhead: TextStyle(),
  subtitle: TextStyle(),
  title: TextStyle(),
),

I want for example have a text with line through then some other have underline etc I was thinking to override the body2 for underline style then how to define another style for line through?

Kind Regards

like image 223
stuckedoverflow Avatar asked Dec 14 '18 06:12

stuckedoverflow


People also ask

How do you create a text theme in Flutter?

Here's how you do it: Step 1: Locate the MaterialApp widget. Step 2: Inside the MaterialApp, add the theme parameter with ThemeData class assigned. Step 3: Inside the ThemeData add the textTheme parameter and then assign the TextTheme .

How do I add themes to my Flutter app?

Making a theme adaptive For this, the values for 'darkTheme' and 'theme' objects must be specified to allow the theme to change to whichever theme is set in the device. By default, the light theme is selected for Flutter applications. However, if only dark theme mode is required, the corresponding value for 'ThemeMode.


2 Answers

You can create a class to hold your style and then call it from anywhere in your app.

class CustomTextStyle {
  static TextStyle display5(BuildContext context) {
    return Theme.of(context).textTheme.display4.copyWith(fontSize: 192.0);
  }
}

And the use it as

Text(
   'Wow',
   style: CustomTextStyle.display5(context),
),

Look at question Flutter: Define custom TextStyles for use throughout the app that contains the complete answer referred here.

like image 71
chemamolins Avatar answered Sep 20 '22 15:09

chemamolins


Here is an alternative using the extension method with the lineThrough:

extension CustomStyles on TextTheme {
 TextStyle get error => const TextStyle(decoration: TextDecoration.lineThrough, fontSize: 20.0, color: Colors.blue, fontWeight: FontWeight.bold);

And then you can use it like this:

Text("your text", style: Theme.of(context).textTheme.error)
like image 21
SK7 Avatar answered Sep 20 '22 15:09

SK7