如何在Flutter文本小部件中进行文本换行?

4

我遇到了一个 RenderFlex溢出了72个像素的问题

这是由于第一个Text()小部件引起的,当用户有非常长的文本时。我甚至尝试使用Textoverflow,但也没有用。

所以我试着像Flutter- wrapping text建议的那样用Flexible来包装它,但它不起作用。你们有什么想法吗?

Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                widget.p.description,
                style: TextStyle(
                  fontWeight: FontWeight.w800,
                ),
                overflow: TextOverflow.ellipsis,
              ),
              SizedBox(height: 4.0),
              Row(
                children: [
                  Text(
                    timeago.format(widget.p.timestamp.toDate()),
                    style: TextStyle(),
                  ),
                  SizedBox(width: 3.0),
                  StreamBuilder(
                    stream: lRef
                        .where('pId', isEqualTo: widget.p.pId)
                        .snapshots(),
                    builder:
                        (context, AsyncSnapshot<QuerySnapshot> snapshot) {
                      if (snapshot.hasData) {
                        QuerySnapshot snap = snapshot.data;
                        List<DocumentSnapshot> docs = snap.docs;
                        return buildCount(context, docs?.length ?? 0);
                      } else {
                        return buildCount1(context, 0);
                      }
                    },
                  ),
                ],
              ),
            ],
          ),
2个回答

11

你需要将文本包装在SizedBox中,然后通过编辑Text小部件的maxLines属性,可以设置多行文本:

示例:

SizedBox(
    //You can define in as your screen's size width,
    //or you can choose a double 
    //ex:
    //width: 100,
    width: MediaQuery.of(context).size.width, //this is the total width of your screen
    child: Text(
      widget.p.description,
      style: TextStyle(
        fontWeight: FontWeight.w800,
      ),
      overflow: TextOverflow.ellipsis,
    ),
  );

同样,您可以像下面所示那样定义文本应该有多少行:

SizedBox(
    //You can define in as your screen's size width,
    //or you can choose a double 
    //ex:
    //width: 100,
    width: MediaQuery.of(context).size.width, //this is the total width of your screen
    child: Text(
      widget.p.description,
      maxLines: 5,
      style: TextStyle(
        fontWeight: FontWeight.w800,
      ),
      overflow: TextOverflow.ellipsis,
    ),
  );


太完美了,这个可行。谢谢! - Spider

2
您也可以使用ConstrainedBox来设置文本的最大长度,这样如果需要的话,它将是多行的:
ConstrainedBox(
  constraints: BoxConstraints(maxWidth: 300),
  child: Text('Any loooooooong text.............................',)
),

请查看官方文档,如果您感兴趣,请点击以下链接: ConstrainedBox类

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接