auto_size_text 2.1.0

#

Travis codecov Version GitHub license

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

Show some ❤️ and star the repo to support the project

Resources: #

Also check out the blazing fast key-value store hive.

Contents #

Usage #

AutoSizeText behaves exactly like a Text. The only difference is that it resizes text to fit within its bounds.

AutoSizeText(
  'The text to display',
  style: TextStyle(fontSize: 20),
  maxLines: 2,
)

Note: AutoSizeText needs bounded constraints to resize the text. More info here.

maxLines #

The maxLines parameter works like you are used to with the Text widget. If there is no maxLines parameter specified, the AutoSizeText only fits the text according to the available width and height.

AutoSizeText(
  'A really long String',
  style: TextStyle(fontSize: 30),
  maxLines: 2,
)

Sample above

minFontSize & maxFontSize

The AutoSizeText starts with TextStyle.fontSize. It measures the resulting text and rescales it to fit within its bonds. You can however set the allowed range of the resulting font size.

With minFontSize you can specify the smallest possible font size. If the text still doesn't fit, it will be handled according to overflow. The default minFontSize is 12.

maxFontSize sets the largest possible font size. This is useful if the TextStyle inherits the font size and you want to constrain it.

AutoSizeText(
  'A really long String',
  style: TextStyle(fontSize: 30),
  minFontSize: 18,
  maxLines: 4,
  overflow: TextOverflow.ellipsis,
)

group #

You can synchronize the font size of multiple AutoSizeText. They will fit their boundaries and all AutoSizeText in the same group have the same size. That means they adjust their font size to the group member with the smallest effective font size.

Note: If a AutoSizeText cannot adjust because of constraints like minFontSize, it won't have the same size as the other group members.

An instance of AutoSizeGroup represents one group. Pass this instance to all AutoSizeText you want to add to that group. You don't have to care about disposing the group if it is no longer needed.

Important: Please don't pass a new instance of AutoSizeGroup every build. In other words, save the AutoSizeGroup instance in a StatefulWidget.

var myGroup = AutoSizeGroup();

AutoSizeText(
  'Text 1',
  group: myGroup,
);

AutoSizeText(
  'Text 2',
  group: myGroup,
);

stepGranularity #

The AutoSizeText will try each font size, starting with TextStyle.fontSize until the text fits within its bounds.
stepGranularity specifies how much the font size is decreased each step. Usually, this value should not be below 1 for best performance.

AutoSizeText(
  'A really long String',
  style: TextStyle(fontSize: 40),
  minFontSize: 10,
  stepGranularity: 10,
  maxLines: 4,
  overflow: TextOverflow.ellipsis,
)

presetFontSizes #

If you want to allow only specific font sizes, you can set them with presetFontSizes. If presetFontSizes is set, minFontSize, maxFontSize and stepGranularity will be ignored.

AutoSizeText(
  'A really long String',
  presetFontSizes: [40, 20, 14],
  maxLines: 4,
)

overflowReplacement #

If the text is overflowing and does not fit its bounds, this widget is displayed instead. This can be useful to prevent text being too small to read.

AutoSizeText(
  'A String tool long to display without extreme scaling or overflow.',
  maxLines: 1,
  overflowReplacement: Text('Sorry String too long'),
)

Rich Text #

You can also use Rich Text (like different text styles or links) with AutoSizeText. Just use the AutoSizeText.rich() constructor (which works exactly like the Text.rich() constructor).

The only thing you have to be aware of is how the font size calculation works: The fontSize in the style parameter of AutoSizeText (or the inherited fontSize if none is set) is used as reference.

For example:

AutoSizeText.rich(
  TextSpan(text: 'A really long String'),
  style: TextStyle(fontSize: 20),
  minFontSize: 5,
)

The text will be at least 1/4 of its original size (5 / 20 = 1/4).
But it does not mean that all TextSpans have at least font size 5.

Parameters #

ParameterDescription
key*Controls how one widget replaces another widget in the tree.
textKeySets the key for the resulting Text widget
style*If non-null, the style to use for this text
minFontSizeThe minimum text size constraint to be used when auto-sizing text.
Is being ignored if presetFontSizes is set.
maxFontSizeThe maximum text size constraint to be used when auto-sizing text.
Is being ignored if presetFontSizes is set.
stepGranularityThe step size in which the font size is being adapted to constraints.
presetFontSizesPredefines all the possible font sizes.
Important: presetFontSizes have to be in descending order.
groupSynchronizes the size of multiple AutoSizeTexts
textAlign*How the text should be aligned horizontally.
textDirection*The directionality of the text. This decides how textAlign values like TextAlign.start and TextAlign.end are interpreted.
locale*Used to select a font when the same Unicode character can be rendered differently, depending on the locale.
softWrap*Whether the text should break at soft line breaks.
wrapWordsWhether words which don't fit in one line should be wrapped. Defaults to true to behave like Text.
overflow*How visual overflow should be handled.
overflowReplacementIf the text is overflowing and does not fit its bounds, this widget is displayed instead.
textScaleFactor*The number of font pixels for each logical pixel. Also affects minFontSize, maxFontSize and presetFontSizes.
maxLinesAn optional maximum number of lines for the text to span.
semanticsLabel*An alternative semantics label for this text.

Parameters marked with * behave exactly the same as in Text

Performance #

AutoSizeText is really fast. In fact, you can replace all your Text widgets with AutoSizeText.
Nevertheless you should not use an unreasonable high fontSize in your TextStyle. E.g. don't set the fontSize to 1000 if you know, that the text will never be larger than 30.

If your font size has a very large range, consider increasing stepGranularity.

Troubleshooting #

Missing bounds #

If AutoSizeText overflows or does not resize the text, you should check if it has constrained width and height.

Wrong code:

Row(
  children: <Widget>[
    AutoSizeText(
      'Here is a very long text, which should be resized',
      maxLines: 1,
    ),
  ],
)

Because Row and other widgets like Container, Column or ListView do not constrain their children, the text will overflow.
You can fix this by constraining the AutoSizeText. Wrap it with Expanded in case of Row and Column or use a SizedBox or another widget with fixed width (and height).

Correct code:

Row(
  children: <Widget>[
    Expanded( // Constrains AutoSizeText to the width of the Row
      child: AutoSizeText(
        'Here is a very long text, which should be resized',
        maxLines: 1,
      )
    ),
  ],
)
}

Further explanation can be found here. If you still have problems, please open an issue.

MinFontSize too large #

AutoSizeText does not resize text below the minFontSize which defaults to 12. This can happen very easily if you use AutoSizeText.rich():

Wrong code:

AutoSizeText.rich(
  TextSpan(
    text: 'Text that will not be resized correctly in some cases',
    style: TextStyle(fontSize: 200),
  ),
)

This rich text does not have a style so it will fall back to the default style (probably fontSize = 14). It has an implicit minFontSize of 12 that means it can be resized to 86% of its original size at the most (14 -> 12). Just set minFontSize = 0 or add style: TextStyle(fontSize: 200) to the AutoSizeText.

Note: If you use the first option, you should also consider lowering stepGranularity. Otherwise the steps of resizing will be very large.

Correct code:

AutoSizeText.rich(
  TextSpan(
    text: 'Text that will be resized correctly',
    style: TextStyle(fontSize: 200),
  ),
  minFontSize: 0,
  stepGranularity: 0.1,
)

MIT License #

Copyright (c) 2018 Simon Leier

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the 'Software'), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

2.1.0 #

  • Added textKey parameter

2.0.2+1 #

  • Fixed screenshots

2.0.2 #

  • Fixed bug where textScaleFactor was not taken into account (thanks @Kavantix)

2.0.1 #

  • Allow fractional font sizes again
  • Fixed bug with wrapWords not working

2.0.0+2 #

  • Added logo

2.0.0 #

  • Significant performance improvements
  • Prevent word wrapping using wordWrap: false
  • Replacement widget in case of text overflow: overflowReplacement
  • Added strutStyle parameter from Text
  • Fixed problem in case the AutoSizeTextGroup changes
  • Improved documentation
  • Added many more tests

1.1.2 #

  • Fixed bug where system font scale was applied twice (thanks @jeffersonatsafe)

1.1.1 #

  • Fixed bug where setting the style of a TextSpan to null in AutoSizeText.rich didn't work (thanks @Koridev)
  • Allow minFontSize = 0

1.1.0 #

  • Added group parameter and AutoSizeGroup to synchronize multiple AutoSizeTexts
  • Fixed bug where minFontSize was not used correctly
  • Improved documentation

1.0.0 #

  • Library is used in multiple projects in production and is considered stable now.
  • Added more tests

0.3.0 #

  • Added textScaleFactor property with fallback to MediaQuery.textScaleFactorOf() (thanks @jeroentrappers)

0.2.2 #

  • Fixed tests
  • Improved documentation

0.2.1 #

  • Fixed problem with minFontSize and maxFontSize (thanks @apaatsio)

0.2.0 #

  • Added support for Rich Text using AutoSizeText.rich() with one or multiple TextSpans.
  • Improved text size calculation (using textScaleFactor)

0.1.0 #

  • Fixed documentation (thanks @g-balas)
  • Added tests

0.0.2 #

  • Fixed documentation
  • Added example

0.0.1 #

  • First Release

example/main.dart

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

void main() {
  runApp(App());
}

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: SizedBox(
            width: 200.0,
            height: 140.0,
            child: AutoSizeText(
              'This string will be automatically resized to fit in two lines.',
              style: TextStyle(fontSize: 30.0),
              maxLines: 2,
            ),
          ),
        ),
      ),
    );
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  auto_size_text: ^2.1.0

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:auto_size_text/auto_size_text.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
99
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
99
Learn more about scoring.

We analyzed this package on Aug 20, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.4.0
  • pana: 0.12.19
  • Flutter: 1.7.8+hotfix.4

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.11 1.14.12
meta 1.1.6 1.1.7
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test
pedantic >=1.4.0 <3.0.0