Automatically resize the text in Flutter

Flutter Aug 2, 2023

In Flutter development, one common challenge is to handle text content that needs to fit within a limited space dynamically. Manually adjusting font sizes for different text lengths can be time-consuming and impractical. Thankfully, there is a Flutter package called auto_size_text, which simplifies this task by automatically resizing the text to fit within the available space. In this post, we will go over the auto_size_text package to demonstrate its functionality and how to implement it.

Installing

To get started, we need to install the auto_size_text package into our project. The installation process is simple. Just execute the following command: flutter pub add auto_size_text.

Once the command is executed, make sure to check your pubspec.yaml file for the added dependencies. You should see the auto_size_text package included in the dependencies section, like this:

dependencies:
  auto_size_text: ^3.0.0
  flutter:
    sdk: flutter

AutoSizeText

The auto_size_text provides two constructors we can use to build auto-sized text widgets. We will start with the regular AutoSizedText constructor which creates a regular AutoSizeText widget, let us go over the implementation:

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Auto Size Text Demo'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                width: 300,
                height: 100,
                padding: EdgeInsets.all(8.0),
                color: Colors.grey[300],
                child: AutoSizeText(
                  'This is an auto-sized text that will adjust its font'
                      ' size to fit within the container.' ,
                  style: TextStyle(fontSize: 30.0),
                  maxLines: 3,
                  minFontSize: 20.0,
                  maxFontSize: 40.0,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              SizedBox(height: 100),
              Container(
                width: 300,
                height: 100,
                padding: EdgeInsets.all(8.0),
                color: Colors.grey[300],
                child: Text(
                  'This is a regular text that will not adjust its font'
                      ' size to fit within the container.',
                  style: TextStyle(fontSize: 30.0),
                  maxLines: 3,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

In this code snippet, we have a Flutter application that shows how the AutoSizeText widget from the auto_size_text package works compared to a regular Text widget when dealing with text that does not fit in a container.

The application has two Container widgets, both with a width of 300 and height of 100. They have a grey background and padding of 8 around the text.

In the first Container widget, we use AutoSizeText to display the text: "This is an auto-sized text that will adjust its font size to fit within the container." The font size of the text automatically changes to fit inside the Container widget. The text is limited to 3 lines, and if it does not fit, it will be cut with an ellipsis. The initial font size is 30.0, but it can go down to 20.0 and up to 40.0 if needed.

In the second container, we use a regular Text widget with a fixed font size of 30.0 to display the text: "This is a regular text that will not adjust its font size to fit within the container." Unlike AutoSizeText, the text will not resize to fit the container. If the text is too long, it will overflow and will not show completely.

When you run the application, you will see the difference: the text inside the first container adjusts to fit perfectly, while the text in the second container overflows and gets cut off.

flutter_displaying_two_containers_with_text_with_on_using_auto_size_text

The AutoSizeText widget comes with quite a lot of properties, click here for the list:

  1. data (String?): The text you want to display within the AutoSizeText widget. 
  2. group (AutoSizeModeGroup?): By assigning the same AutoSizeModeGroup instance to multiple AutoSizeText widgets, they will share the same font size, ensuring consistent text sizing across those widgets.
  3. locale (Locale?): Used to select a font when the same Unicode character can be rendered differently, depending on the locale. It allows you to specify a specific locale to adjust the font rendering appropriately.
  4. maxFontSize (double): The maximum text size constraint to be used when auto-sizing text. This property determines the upper limit of the font size that AutoSizeText can use to fit the text within the available space. Default: double.infinity.
  5. maxLines (int?): An optional maximum number of lines for the text to span, wrapping if necessary. If the text exceeds the given number of lines, it will be resized according to the specified bounds and, if necessary, truncated according to overflow.
  6. minFontSize (double): The minimum text size constraint to be used when auto-sizing text. This property determines the lower limit of the font size that AutoSizeText can use to fit the text within the available space. Default: 12.
  7. overflow (TextOverflow?): How visual overflow should be handled. This property defines how the text is displayed when it overflows the available space. Options include clipping, ellipsis, fading, or simply showing the overflow.
  8. overflowReplacement (Widget?): If the text is overflowing and does not fit its bounds, this widget is displayed instead. You can provide a replacement widget to handle situations when the text overflows.
  9. presetFontSizes (List<double>?): Predefines all the possible font sizes. This property allows you to specify a list of font sizes that AutoSizeText can use for resizing the text. If provided, AutoSizeText will choose the closest preset font size that fits within the available space.
  10. semanticsLabel (String?): An alternative semantics label for this text. You can use this property to provide accessibility labels for screen readers or other accessibility features.
  11. softWrap (bool?): This property determines whether the text should wrap at word boundaries to fit within the available width. If set to true, the text will break into multiple lines at natural word boundaries, ensuring it fits within the available space.
  12. stepGranularity (double): This property determines how much the font size should be adjusted at a time when resizing the text to fit within the constraints. It defines the step size of font size adjustment, allowing more precise control over how the text scales when it doesn't fit within the available space. Default: 1.
  13. strutStyle (StrutStyle?): This property allows you to ensure consistent vertical spacing for the text. The StrutStyle defines the minimum vertical layout metrics, ensuring that the text maintains consistent spacing between lines, even if some lines have larger font sizes or taller characters. It helps maintain a visually pleasing and harmonious layout for the text.
  14. style (TextStyle?): This property allows you to define the text style for the AutoSizeText. You can set various text attributes, such as font family, font size, color, and more, using this property.
  15. textAlign (TextAlign?): How the text should be aligned horizontally. This property controls the horizontal alignment of the text within the AutoSizeText widget.
  16. textDirection (TextDirection?): The direction of the text, either TextDirection.ltr (left-to-right) or TextDirection.rtl (right-to-left). Default: TextDirection.ltr.
  17. textKey (Key?): Sets the key for the resulting Text widget. This property allows you to provide a specific key for the underlying Text widget created by AutoSizeText.
  18. textScaleFactor (double?): This property allows you to globally scale the font size of the text. It specifies the ratio of font pixels to logical pixels, enabling you to make the text larger or smaller throughout the entire widget tree.
  19. textSpan (TextSpan?): The text to display as a TextSpan. This property allows you to use rich text and apply different styles to specific portions of the text. Default: null.
  20. wrapWords (bool): Whether words that do not fit in one line should be wrapped. If set to true, AutoSizeText will wrap words that do not fit in a single line to the next line. Default: true.

AutoSizeText.rich

AutoSizeText.rich is a constructor of the AutoSizeText widget in Flutter that allows you to display rich text with inline styling. In Flutter, rich text refers to text that contains multiple styles within the same text span, such as different font sizes, colors, font families, and more.

The AutoSizeText.rich widget takes a TextSpan as its child, which allows you to define the inline styles for different parts of the text. The TextSpan can contain nested children, each with its own set of style attributes.

Here is an example of how to use AutoSizeText.rich constructor:

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Auto Size Text Demo'),
        ),
        body: Center(
          child: AutoSizeText.rich(
            TextSpan(
              text: 'Welcome ',
              style: TextStyle(fontSize: 24, color: Colors.black),
              children: [
                TextSpan(
                  text: 'to',
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    color: Colors.blue,
                  ),
                ),
                TextSpan(
                  text: ' Code Onwards!',
                  style: TextStyle(
                    fontStyle: FontStyle.italic,
                    color: Colors.green,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

In this example, the AutoSizeText.rich widget displays the text "Welcome to Code Onwards!" with different styles for each part of the text. The word "Welcome" is bold and larger, the word "to" is bold and blue, while the phrase "Code Onwards!" is italic and green.

flutter_displaying_rich_text_with_different_styling_across_the_sentence

With AutoSizeText.rich, you can create fancy text layouts with different styles, making it a helpful tool for showing stylish and rich text in your Flutter application.

Use cases

The AutoSizeText widget is really fast. In fact, you can replace all your Text widgets with AutoSizeText. Here are some use cases:

1. Responsiveness

To create well-designed applications that look great on various screen sizes and orientations, the auto_size_text package can be very convenient. It automatically adjusts the font size of text elements based on the device's screen width, ensuring the text remains legible and fits well on any screen.

2. Buttons with Dynamic Text

When buttons have text that can change dynamically based on the application's state, using AutoSizeText prevents text overflow or wrapping issues. The widget automatically resizes the font size of the button's text to fit perfectly within the available space.

3. Text inside Cards or Tiles

For displaying dynamic content like news articles or social media posts within cards or tiles, AutoSizeText is useful. It ensures that the text adjusts and fits correctly within the container without overflowing, providing a clean and polished appearance for the content.

Conclusion

The auto_size_text package is a valuable tool in Flutter development that simplifies handling dynamic text sizing. It allows you to create responsive and adaptive user interfaces with text that automatically adjusts its font size to fit within available space. By replacing the Text widgets with the AutoSizeText widgets, you can ensure a great user experience and visually appealing text elements in your Flutter applications.

Tags