Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

dart - How to design a Text Widget that wraps automatically in flutter?

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,
  ),
),

enter image description here

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.

How can I improve the code?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can try this approach:

@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,
        ),
      ),
    ),
  );
}

Output:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...