Flutter アプリ

【Flutter】FittedBoxのBoxFit.scaleDownで、文字の大きさがいい感じになった

以下の画面を開発しているのですが、ケーブルロウだけ文字が大きく、アンバランスな感じです。どのような文字が入ってもフォントサイズは小さく表示させたいです。

本記事の想定読者

  • Flutterでアプリを開発している人

開発環境

$ flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 3.0.5, on Microsoft Windows [Version 10.0.19045.3208], locale ja-JP)
[√] Android toolchain - develop for Android devices (Android SDK version 32.0.0)
[√] Chrome - develop for the web
[√] Visual Studio - develop for Windows (Visual Studio Community 2022 17.1.4)
[√] Android Studio (version 2021.1)
[!] Android Studio (version 4.1)
    X Unable to determine bundled Java version.
[!] Android Studio (version 4.2)
    X Unable to determine bundled Java version.
[√] VS Code (version 1.81.0)
[√] Connected device (4 available)
[√] HTTP Host Availability

! Doctor found issues in 2 categories.

pubspec.yaml

dependencies:
  flutter:
    sdk: flutter


  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  sticky_grouped_list: ^3.1.0
  intl: ^0.18.1
  google_fonts: ^4.0.4
  sqflite: ^2.0.3+1
  numberpicker: ^2.1.2

コードを見てみよう

冒頭の画面になるときのコードは以下の通りです。

FittedBoxでTextウィジェットがoverflowしないようにFittedBoxを使用していますが、そのプロパティはBoxFit.fitWidthです。

BoxFit.fitWidthは、親要素から垂直方向にはみ出しても、子要素の幅はおさまるように表示するものです。つまり、縦の長さは変わりません。

                   child: FittedBox( // 文字の自動縮小
                        fit: BoxFit.fitWidth,
                        child: Text(
                          widget.exercise,
                          style: TextStyle(
                            fontSize: 20,
                          ),
                        ),
                      ),

文字を縮小させるには、BoxFit.scaleDownがいい

文字を縮小させるには、BoxFit.scaleDownを選択する事です。BoxFit.scaleDownは、子要素を親要素に配置(デフォルトはセンタリング)し、必要に応じて小さくおさまるように表示させるものです。

                   child: FittedBox( // 文字の自動縮小
                        fit: BoxFit.scaleDown,
                        child: Text(
                          widget.exercise,
                          style: TextStyle(
                            fontSize: 20,
                          ),
                        ),
                      ),

BoxFit.scaleDownを選択したときの文字の大きさはこんな感じです。ケーブルロウの文字がいい感じで小さくなったでしょ。

-Flutter, アプリ