如何设计一个自动在颤动中自动换行的Text Widget? [英] How to design a Text Widget that wraps automatically in flutter?

查看:79
本文介绍了如何设计一个自动在颤动中自动换行的Text Widget?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设计一个自动换行的文本小部件,当文本长度超过最大长度时,它会使用省略号.

I want to design a text widget that wraps automatically, and it uses an ellipsis when the text length exceeds the maximum.

以下代码可以达到类似的效果.

The following code can achieve a similar effect.

Container(
  color: Colors.red,
  child: Text(
    'DENTIFICATIONDENTIFICATIONDENTIFICATIONDENTIFICATIONDENTIFICATIONDENTIFICATIONDENTIFICATIONDENTIFICATIONDENTIFICATIONDENTIFICATIONDENTIFICATIONDENTIFICATIONDENTIFICATIONDENTIFICATIONDENTIFICATIONDENTIFICATIONDENTIFICATIONDENTIFICATIONDENTIFICATIONDENTIFICATION',
    overflow: TextOverflow.ellipsis,
    maxLines: 6,
  ),
),

但是它必须指定maxLines,我不希望这样,我需要小部件根据父项的大小自动设置maxLines.

But it must specify maxLines, I don't want this, I need the widget to automatically set the maxLines based on the size of parent.

如何改进代码?

推荐答案

您可以尝试以下方法:

@override
Widget build(BuildContext context) {
  String longText = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum";
  double size = 100, fontSize = 16; 

  return Scaffold(
    appBar: AppBar(),
    body: Padding(
      padding: const EdgeInsets.all(20.0),
      child: SizedBox(
        height: size,
        child: Text(
          longText,
          style: TextStyle(fontSize: fontSize, height: 1),
          overflow: TextOverflow.ellipsis,
          maxLines: size ~/ fontSize,
        ),
      ),
    ),
  );
}

输出:

这篇关于如何设计一个自动在颤动中自动换行的Text Widget?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆