🐙
text_style_previewでFlutterのTextStyleを混乱せず選ぶ
はじめに
FlutterでUIを組んでいる時、TextThemeのheadlineSmall、bodyMediumといったType Scaleを選ぶ際に迷ったことはありませんか?
Material Design 3では5つのロール(Display、Headline、Title、Body、Label)とロールごとに3つのサイズ(Large、Medium、Small)で、合計15個のType Scaleがあり、これらの中から選ぶことで一貫性のある体験を実現できるとされています。
https://m3.material.io/styles/typography/type-scale-tokens
理想としてはUIのどの部分を作るかでType Scaleが自然に決まることですが、迷うこともあると思います。この記事ではType Scaleを選ぶのをサポートするtext_style_previewパッケージを紹介します。
基本の使い方
1. パッケージのインストール
pubspec.yaml ファイルに text_style_preview を追加し、flutter pub get
dependencies:
text_style_preview: <任意のバージョン>
```text
<https://pub.dev/packages/text_style_preview>
## 2. Textウィジェットを囲む
TextStyleを決めたいTextウィジェットをTextStylePreviewウィジェットで囲みます
```dart
const TextStylePreview(
child: Text('Sample Text'),
),
```text
## 3. Textをタップするとプレビューが表示される

# カスタマイズして使う
## 特定のウィジェットに対してカスタマイズする
initTypeScaleCategory、applyCustomStyle、styleなどを指定することでカスタマイズできます。
initTypeScaleCategory:初期選択されるType Scale。
applyCustomStyle:TextThemeのTextStyleをカスタマイズするときに使えます。文字色を変えるなどで使えます。
style:プレビューウィンドウの見た目を調整できます。
```dart
TextStylePreview(
initTypeScaleCategory: TypeScaleCategory.headlineSmall,
applyCustomStyle: (textStyle) => textStyle.apply(
color: Colors.blue,
fontSizeFactor: 1.5,
),
// set stye like this
style: TextStylePreviewStyle(
modalHeight: 300,
barrierColor: Colors.transparent,
showDivider: true,
descriptionBuilder: (typeScaleCategory, textStyle) =>
typeScaleCategory.name,
),
child: const Text('Sample Text2'),
),
```text
## アプリ全体をカスタマイズする
TextStylePreviewStyleがThemeExtensionに対応しているので、MaterialAppで共通のstyleを指定できます。
```dart
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
useMaterial3: true,
primarySwatch: Colors.red,
// set default stye like this
extensions: const [
TextStylePreviewStyle(
showDivider: false,
),
],
),
home: const TextStylePreviewDemoScreen(),
);
}
ThemeExtensionの解説動画
https://www.youtube.com/watch?v=8-szcYzFVao
最後に
気に入ったらぜひ使ってみてください👇
https://pub.dev/packages/text_style_preview
Discussion