Flutter tutorials

How to Automatically Resize Flutter font size based on screen size

Automatically resize Flutter font size based on screen size accordingly to the width and height dimension of the device. There’re so many dimensions of mobile devices and because of that it very vital that you adjust the font size of your text to improve user experience. If you set a static pixel of your app font size for all devices, it will appear smaller on big screens and larger on small screens. But that’s not the best, so let me show you examples of how you can do it properly without breaking the widget tree.

There are so many ways to do this either you prefer to do it manually or by using a third-party package. First let use the Flutter auto_size_text package to resize font size based on the screen size. You need to add the dependency to your pubspec.yaml file (check for the latest version number)

dependencies:
  flutter:
    sdk: flutter
#this is the latest version number at the time of writing this post
  auto_size_text: ^3.0.0

Then in your main.dart file or any other activity where you want to adjust a particular text font size, import the package:

import 'package:auto_size_text/auto_size_text.dart';

Now, you need to remember the golden rule when working with Flutter “Everything is widget” So you need to use the AutoSizeText() widget instead of Text() widget to render a text.

AutoSizeText(
  'My first Flutter application',
  style: TextStyle(fontSize: 30),
  maxLines:3,
)

Set the maxLines parameter to any number of lines you want the text to expand. This is auto resizing, meaning it will be adjusted accordingly to the device size and you can include minimum and maximum font-size too.

AutoSizeText(
  'Flutter auto resize text font',
  style: TextStyle(fontSize: 15),
  minFontSize: 10,
  maxLines: 3,
  overflow: TextOverflow.ellipsis,
)

Also, while resizing the font-size, you have the option to set pre-defined font size t be adapt accordingly.

AutoSizeText(
  ‘Fluter resizing text font example',
  presetFontSizes: [50, 30, 16],
  maxLines: 4,
)

Flutter full code to adjust font size based on screen size

import 'package:auto_size_text/auto_size_text.dart';
import 'package:flutter/material.dart';


Future<void> main() async {
  runApp(MyApp());
}
// you could also use a stateful widget depending on the project requirement
class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget{
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) { 
    return  Scaffold(
          appBar: AppBar( 
              title: Text("Auto Resize Text"),
              backgroundColor: Colors.redAccent,
          ),
          body: Container( 
            padding: EdgeInsets.all(22),
            child: Column(
               children:[
                     AutoSizeText(
                       "dynamically adjusting font size in flutter",
                       maxLines:2,
                       style: TextStyle(fontSize:50),
                    ),

                     AutoSizeText(
                       "Lorem Ipsum is simply dummy text of the printing" + 
                       "and typesetting industry. Lorem Ipsum has",
                       maxLines:8,
                       style: TextStyle(fontSize:40),
                    ),

                    AutoSizeText(
                       "Lorem Ipsum is simply dummy text of the printing" + 
                       "and typesetting industry. Lorem Ipsum has been " +  
                       "the industry's standard dummy text",
                       maxLines:3,
                       style: TextStyle(fontSize:20),
                    ),

               ]
            )
          ),
           
       );
  }
}

Solution Two: Using FittedBox() widget to Resize font-size:

Depending on the width of the appBar, you can wrap a text in a FittedBox() widget and the font will be resize based on the appBar width dynamically.

AppBar(
    centerTitle: true,
    title: FittedBox(
        fit: BoxFit.fitWidth, 
        child: Text('My flutter center appbar title')
    ),
)

Check also, How to solve null check operator used on a null value?

Solution Three: Use MediaQuery to resize font size in flutter based on screen size

MediaQuery provide information about the device or the emulator both portrait and landscape mode. So, depending on the mode of the device, you can use the MediaQuery class to retrieve the device height and width. And because of that we can easily use it to adjust different widgets like Containers and Text font sizes in the application.

First create a separate file UserDeviceSize.dart and copy and past below code. I have explain the code very well with comments, please take your time to understand. All that is doing is providing information about the device dimensions.

import 'package:flutter/material.dart';

// method to return the size object of the user screen
Size displayUserDeviceSize(BuildContext context) {
  //print('Size = ' + MediaQuery.of(context).size.toString());
  return MediaQuery.of(context).size;
}

// method to return the height of the user device screen
double userDeviceHeight(BuildContext context) {
  // print('Height = ' + displayUserDeviceSize(context).height.toString());
  return displayUserDeviceSize(context).height;
}

// method to return the width of the user device screen
double userDeviceWidth(BuildContext context) {
  // print('Width = ' + displayUserDeviceSize(context).width.toString());
  return displayUserDeviceSize(context).width;
}

You can now make use of the above code in your main.dart file or any other activity you want to adjust widget dimensions dynamically.

import 'package:flutter/material.dart';
// import the above file
import '../../../constants/UserDeviceSize.dart';


Future<void> main() async {
  runApp(MyApp());
}
// you could also use a stateful widget depending on the project requirement
class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget{
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) { 
    return  Scaffold(
          appBar: AppBar( 
              title: Text("Auto Resize Text"),
              backgroundColor: Colors.redAccent,
          ),
          body: Container( 
            padding: EdgeInsets.all(22),
            child: Column(
               children:[
Text("Quick Delivery Insight",
   // dynamically change the font-size here
   userDeviceWidth(context) * 0.05, 
  FontWeight.w600)
),

               ]
            )
          ),
           
       );
  }
}

Related Posts

Flutter vs React Native

5 Reasons Why You Should Choose Flutter Over React Native In 2023

Are you confused about choosing between Google Flutter and React Native for your next cross-platform-app? Well, in this article I will show you reasons why Flutter is much…

flutter-error-setstate-called-after-dispose

[Solved] Vertical viewport was given unbounded height Error in flutter

When you include Listview as child widget of Scroll view and a Column or when you try to create a UI that leads you to use gride-layout, you…

working with list in Dart/Flutter

How to use Conditional Statement (IF ELSE) on Child Widget in Flutter

Flutter conditionally show widget within child attribute using (if else) statement or ternary operator. This can be very overwhelming for beginners because you can’t directly use “if..else” statement…