[Flutter]Text(テキスト)のスタイルにThemeを適用するには?

Flutter

どうも、ちょげ(@chogetarou)です。

TextのスタイルをThemeで設定する方法を紹介します。

スポンサーリンク

方法

インターフェース, インターネット, プログラム, ブラウザ, Www

TextのスタイルをThemeで設定するには、Textの引数「style」を使います。

具体的には、Textの引数「style」に、TextThemeの設定したいプロパティを指定します。

Text(
    'Hello, Flutter',
    style: Theme.of(context).textTheme.〇〇, //〇〇はTextThemeのプロパティ名
),

Textの引数「style」に「Theme.of(context).textTheme.〇〇」を指定することで、TextThemeのプロパティのTextStyleがTextに適用されます。

TextTheme自体の設定は、ThemeDataの引数「textTheme」でします。

Theme(
  data: ThemeData(
    textTheme: TextTheme(/*設定*/)
  ),
),

使用例

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: Sample(),
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        textTheme: TextTheme(
          headline1: TextStyle(
            fontSize: 24,
            fontWeight: FontWeight.bold,
          ),
          headline2: TextStyle(
            fontSize: 18,
            fontStyle: FontStyle.italic,
          ),
          headline3: TextStyle(
            fontSize: 10,
            fontWeight: FontWeight.w200,
          ),
        ),
      ),
    );
  }
}

class Sample extends StatelessWidget {
 
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Theme(
        data: ThemeData(
          textTheme: TextTheme(
            headline1: TextStyle(
              fontSize: 24,
              fontWeight: FontWeight.bold,
            ),
            headline2: TextStyle(
              fontSize: 18,
              fontStyle: FontStyle.italic,
            ),
            headline3: TextStyle(
              fontSize: 10,
              fontWeight: FontWeight.w200,
            ),
          ),
        ),
        child: Scaffold(
          body: Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  'Hello, Flutter',
                  style: Theme.of(context).textTheme.headline1,
                ),
                Text(
                  'Hello, Flutter',
                  style: Theme.of(context).textTheme.headline2,
                ),
                Text(
                  'Hello, Flutter',
                  style: Theme.of(context).textTheme.headline3,
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

コメント

タイトルとURLをコピーしました