LoginSignup
1
1

More than 1 year has passed since last update.

[Flutter] スタイルのcopyWithは良いけどテーマだと気を付けないといけない面倒な話

Posted at

こんにちは、Flutter赤ん坊です。

今回はたいそう無駄な実験を、しこたま白熱した熱気に包まれたPCファンの音を聴きながら、せっせことこなしました。考えたら当たり前のことを実験するのは、はたして無駄なのかそうでないのか、皆様のご意見にゆだねます。

事の発端

テーマを使い回せば良いとはよく言われているのですが、使い回し方がいまいちよくわからない。copyWithで元々あるテーマを使いまわせるのはわかるけど、何かもやっとして色々調べるも、自分で試した方が早いんじゃないかと言う思いにかられ、やってしまいました。

試した事

とりあえず一つの要素のみ適用したスタイル3つを設定し、それらをcopyWithとmergeで合成しました。最後に、テーマとしてcopyWithで合成してみました。

// 単体
final large = TextStyle(fontSize: 30);
final red = TextStyle(color: Colors.red);
final line = TextStyle(decoration: TextDecoration.lineThrough);

// スタイル合成
final copy = large
    .copyWith(color: Colors.red)
    .copyWith(decoration: TextDecoration.lineThrough);
final merge = large.merge(red).merge(line);

// テーマ合成
final copyTheme = ThemeData(textTheme: TextTheme(headline1: large))
    .copyWith(textTheme: TextTheme(headline1: red))
    .copyWith(textTheme: TextTheme(headline1: line));

これらを以下のコードで表示します。

Column(
  mainAxisAlignment: MainAxisAlignment.center,
  children: <Widget>[
    Text("--- 単体 ---"),
    Text("large", style: large),
    Text("red", style: red),
    Text("line", style: line),
    Text("\n--- スタイル合成 ---"),
    Text("copy", style: copy),
    Text("merge", style: merge),
    Text("\n--- テーマ合成 ---"),
    Text("copy theme", style: copyTheme.textTheme.headline1),
  ],
)

結果

スクリーンショット 2021-09-22 10.16.15.png

スタイルのみをcopyWithやmergeしたものは、いずれもうまく合成できています。一方テーマをcopyWithしたものは、最後のスタイルのみ適用されていますね。

以上のことから、本気でテーマを合成しようとしたら、スタイル一つ一つに対してcopyWithやmergeをかけないといけないようです。実に面倒臭い事実に気付いてしまったわけですが、もやっとが解消されたので良かった事にしておきます。

以上です。夏が終わりに近づいていますが、ごきげんよう。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1