【 Flutter 】Flutter を 基礎 から 学習 ( ウィジェット編 ) part02 基本的なウィジェット

基礎 から 学ぶ Flutter 」という書籍で  学習 したことを ブログでアウトプットしていこうと思います。今回は ウィジェット編 ( part02 )です。

前回

【 Flutter 】Flutter を 基礎 から 学習 ( ウィジェット編 ) part01 基本的なウィジェット

引き続き、基本的なウィジェットについて学びます。

基本的なウィジェット

Text,RichTextウィジェット

styleプロパティ

TextStyleクラスをインスタンスすることは稀です。

と、冒頭に記述されていますがなんのことだか笑

おそらく前回使用した「★」の部分について記述した内容だと思います。

    var rich = Text.rich(TextSpan(text: 'こんにちは', children: <TextSpan>[
      TextSpan(text: ' 美しい ', style: ★TextStyle(fontStyle: FontStyle.italic)),
      TextSpan(text: ' 世界 ', style: ★TextStyle(fontWeight: FontWeight.bold)),
    ]));

このTextStyleの代替がTextThemeクラスになります。

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      // home: MyHomePage(title: 'Flutter Demo Home Page'),
      initialRoute: '/',
      routes: {
        '/': (context) => FirstPage(),
      },
    );
  }
}

class FirstPage extends StatelessWidget {
  Widget build(BuildContext context) {
    final ThemeData theme = Theme.of(context);
    final TextTheme textTheme = theme.textTheme;
    // final titleStyle = textTheme.title.copyWith(color: theme.backgroundColor); ←titleプロパティは非推奨になりました。
    final titleStyle =
        textTheme.headline6!.copyWith(color: theme.backgroundColor);// このように、TextThemeの一部をコピーして使うそうです。

    return Scaffold(
      appBar: AppBar(
          title: /*const はダメ*/ Text(
        'First Page',
        style: titleStyle,
      )),
      //body: Text('本文', style: textTheme.body1), ← body1プロパティは非推奨のようです。
      body: Text('本文', style: textTheme.bodyText1),
    );
  }
}

サンプルにも記述しましたが、TextThemeのtitleプロパティは非推奨となり、headline6を使う必要があるとのことです。
また、body1も非推奨になちました。こちらはたぶんbodyText1を使えばよいようです。

Flutter styleの’title’はdeprecatedになり’headline6’になった模様。 – Qiita

 

実行すると以下のように表示されました。

ん~・・・よくわかりません(笑

最後に

スタイルはTextThemeクラスをインスタンスしてcopyWithを使用し一部分だけ使用するということだと思います。

今日はここまで!