skip to Main Content

I was specifying the textSize in the textTheme of ThemeData.

 textTheme: const TextTheme(
    displayLarge: TextStyle(
      color: Colors.black,
      letterSpacing: 4,
      fontSize: 25,
    ),
    displayMedium: TextStyle(
      color: Colors.black,
      letterSpacing: 2,
      fontSize: 18,
    ),
  ),

However, with this approach, the text may become extremely small on some devices. Therefore, you need to obtain the device’s size and specify the fontSize as follows.

fontSize: MediaQuery.of(context).size.width * 0.01,

Since context is required, it’s not possible to obtain the device’s size within ThemeData. Therefore, it seems that specifying fontSize using TextTheme in ThemeData may not be the best practice.

How do you all specify the fontSize?

3

Answers


  1. You can check flutter_screenutil package, or write utility function that will be using context:

    TextStyle myTextStyle(BuildContext context) {
      return TextStyle(
        fontSize: MediaQuery.of(context).size.width * ... ,
      );
    }
    
    Login or Signup to reply.
  2. Use textScaleFactor for adjusting scale globally with MaterialApp.builder.

    return MaterialApp(
      ...
      builder: (context, child) {
        var defaultScaleFactor = MediaQuery.maybeOf(context)?.textScaleFactor ?? 1.0
        defaultScaleFactor += MediaQuery.of(context).size.width / 1000;
        var clamppedScaleFactor = clampDouble(defaultScaleFactor, 0.7, 1.3);
        return MediaQuery(
          data: MediaQuery.of(context).copyWith(textScaleFactor: clamppedScaleFactor),
          child: child ?? emptyWidget,
        );
      },
    );
    

    Caution: Respect Accessbility about Large Font. Dont overuse or fix textScaleFactor. It is more natural limit range of textScaleFactor and weighted factor on screen size.

    Login or Signup to reply.
  3. You can use auto_size_text package.

    Flutter widget that automatically resizes text to fit perfectly within its bounds.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search