[Flutter] RichText って何?

FlutterのRichTextは、複数のテキストスタイルを含むテキストを表示するために使用されます。RichTextウィジェットは、TextSpanウィジェットを使用して構築されます。TextSpanウィジェットは、親ウィジェットにテキストのスパンを追加するためのメソッドを提供します。

目次

1. RichTextウィジェットを作成する

RichTextウィジェットを作成します。RichTextウィジェットは、TextSpanウィジェットを含む必要があります。次のように、テキストとスタイルを含むTextSpanウィジェットを作成し、RichTextウィジェットに追加します。

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My App',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('RichText Example'),
      ),
      body: Center(
          child: RichText(
        text: TextSpan(
          text: 'Hello ',
          style: TextStyle(color: Colors.black, fontSize: 18),
          children: <TextSpan>[
            TextSpan(
                text: 'Flutter', style: TextStyle(fontWeight: FontWeight.bold)),
            TextSpan(text: ' World!'),
          ],
        ),
      )),
    );
  }
}

2. テキストスパンを定義する

テキストスパンを定義し、TextSpanウィジェットに追加します。テキストスパンは、特定のテキストのスタイルを定義します。以下は、テキストスパンを定義する例です。(上記サンプルコードのRichTextウィジット部分を以下に置き換えます)

RichText(
  text: TextSpan(
    text: 'Hello ',
    style: TextStyle(color: Colors.black, fontSize: 18),
    children: <TextSpan>[
      TextSpan(
          text: 'Flutter', style: TextStyle(fontWeight: FontWeight.bold, color: Colors.blue)),
      TextSpan(text: ' World!'),
    ],
  ),
)

上記の例では、”Flutter”というテキストに太字のスタイルを適用しています。

3. テキストスパンをネストする

テキストスパンは、他のテキストスパンを含むことができます。これにより、より複雑なスタイルを定義することができます。以下は、ネストされたテキストスパンを定義する例です。

RichText(
  text: TextSpan(
    text: 'Hello ',
    style: TextStyle(color: Colors.black),
    children: <TextSpan>[
      TextSpan(
        text: 'Flutter',
        style: TextStyle(fontWeight: FontWeight.bold, fontSize: 24),
        children: <TextSpan>[
          TextSpan(
              text: ' World!',
              style: TextStyle(color: Colors.blue, fontSize: 30)),
        ],
      ),
    ],
  ),
)

上記の例では、”Hello “というテキストに黒色のスタイルを適用し、”Flutter”というテキストに太字のスタイルを適用して、”World!”というテキストに青色のスタイルを適用しています。

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!
目次