世界最大級のオンライン学習サービス「Udemy」のセール状況はこちら

【Flutter】Textの改行|文字列を任意の位置で改行・中央揃えする

「Textの文字列を改行させたい」

こんな悩みを解消します。

今回はTextの文字列を改行させる方法と改行させた文字列を中央揃えまたは左揃えにする方法について解説していきます!

目次

方法

Textを改行させる方法を2つ解説します。

\nで改行させる

1つ目の方法はTextの文字列で改行させたい位置に\nを追加する方法です。

Text(
  'Hello\nNewWorld',
  style: TextStyle(fontSize: 60),
),

トリプルクオーツで改行

2つ目の方法はTextの文字列をトリプルクオーツ'''を使用して改行させる方法です。

文字列を'''で囲んだコードの改行がそのままTextに反映されます。同時に文字列の左側の空白も反映されてしまうので注意が必要です。

Text(
  '''Hello
     NewWorld''', //Nの左側の空白が反映される
  style: TextStyle(fontSize: 40),
),
画像のサンプルコード
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: MyWidget(),
    );
  }
}

class MyWidget extends StatelessWidget {
  const MyWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Flutter')),
      body: Center(
        child: Text(
          '''Hello
     NewWorld''',
          style: TextStyle(fontSize: 40),
        ),
      ),
    );
  }
}

改行させた文字列を中央表示させる

Textで改行させた文字列を中央表示させるにはtextAlignプロパティで設定できます。

textAlignの引数にTextAlign.centerを渡せば中央、TextAlign.leftを渡せば左側に文字列が表示されます。

Text(
  'Hello\nNewWorld',
  style: TextStyle(fontSize: 60),
  textAlign: TextAlign.center,
),

まとめ

今回はTextの文字列を改行させる方法について解説しました。

次の記事でTextのカスタマイズ方法について解説しているのでぜひ一緒にご覧ください。

目次