概要
この記事はFlutterにおいて、MaterialThemeのTypographyをテキストスタイルに適用させるための実装方法をまとめたものです。
MaterialThemeのTypographyについて
テキストスタイルを変えたい場合、フォントの種類やらフォントサイズやらフォントウェイトやらを自分で設定するのはかなり面倒だと感じたことのある人は多いはず。そんな時にMaterialThemeを用いればGoogleさんのデザイナーが良さげなテキストスタイルを用意してくれることによってデザインに掛かるコストを下げることやユーザビリティの向上にも役立ちます。
詳しくは
どんな種類があるの?
具体的にはheadline1
, headline2
, headline3
, headline4
, headline5
, headline6
, subtitle1
, subtitle2
, bodyText1
, bodyText2
, caption
, button
, overline
の計13個です。headline1はhtmlのh1タグとほぼ同義なので分かりやすいですね。
実装方法
import 'package:flutter/material.dart';
void main() {
runApp(const TextThemeApp());
}
class TextThemeApp extends StatelessWidget {
const TextThemeApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Text Theme App',
home: Scaffold(
appBar: AppBar(
title: Text('Text Theme App'),
),
body: Center(
child: Column(
children: [
Text('headline1', style: Theme.of(context).textTheme.headline1),
Text('headline2', style: Theme.of(context).textTheme.headline2),
Text('headline3', style: Theme.of(context).textTheme.headline3),
Text('headline4', style: Theme.of(context).textTheme.headline4),
Text('headline5', style: Theme.of(context).textTheme.headline5),
Text('headline6', style: Theme.of(context).textTheme.headline6),
Text('subtitle1', style: Theme.of(context).textTheme.subtitle1),
Text('subtitle2', style: Theme.of(context).textTheme.subtitle2),
Text('bodyText1', style: Theme.of(context).textTheme.bodyText1),
Text('bodyText2', style: Theme.of(context).textTheme.bodyText2),
Text('caption', style: Theme.of(context).textTheme.caption),
Text('button', style: Theme.of(context).textTheme.button),
Text('overline', style: Theme.of(context).textTheme.overline),
],
),
),
),
);
}
}
プレビュー
注意点
このテーマはcontectを引数としているので、必ず Widget build(BuildContext context)
配下に適用させないとエラーになります。
フォントを変えたい
かといってデフォルトのフォントでは気に入らない場合があると思います。その場合はgoogle_fonts
をインストールします。
フォントの検索はこちらから、日本語に最適化されたフォントが用意されているので私はこちらをおすすめします。
変更点
Text(
'headline1',
style: GoogleFonts.mPlusRounded1c( // フォントを変えたい場合はここで指定する
textStyle: Theme.of(context).textTheme.headline1),
),
おわりに
今回はMaterialThemeを用いたTypographyの実装方法の紹介でした。他にもカラーやアイコンについて、詳しくはこの方の記事などが参考になりました。