首页 > 解决方案 > Flutter Text 仅在空格处换行

问题描述

我的问题是颤动会在非空白字符处破坏文本:

在此处输入图像描述

我怎样才能告诉颤振不要在“/”处敲击文本,而只有在遇到空格时才可以?

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: Scaffold(
        body: Center(
          child: Container(
            width: 220.0,
            child: Text(
              'This should not break here x/y/z',
              style: TextStyle(fontSize: 30.0),
            ),
          ),
        ),
      ),
    );
  }
}

我一直在研究像 auto_size_text 这样的包,但没有找到解决这个问题的方法。

编辑:

使用 '\n' 不是一个选项,因为文本的长度会有所不同,但它总是包含三个 x/y/z 字符,最后用斜线分隔。

我宁愿不提前计算渲染文本的大小来确定是否应该在 x/y/z 之前包含换行符。这似乎有点重,因为这些是包含在 ListView 中的卡片标题。

在网络上没有问题,文本只在空格处被破坏:

<!DOCTYPE html>
<html>

<body>
    <div style="background-color: grey; height: 200px; width: 400px;">
        <p style="font-size: 24.0pt;">
            This should not break here x/y/z
        </p>
    </div>
</body>

</html>

标签: flutterflutter-layoutflutter-text

解决方案


我通常使用TextAlign.justify适合文本,并且根据我的喜好,您可以尝试:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: Scaffold(
        body: Center(
          child: Container(
            width: 220.0,
            child: Text(
              'This should not break here x/y/z',
              textAlign: TextAlign.justify,
              style: TextStyle(fontSize: 30.0),
            ),
          ),
        ),
      ),
    );
  }
} 

TextAlign.center不错。


推荐阅读