Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.9k views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share

548k questions

547k answers

4 comments

56.5k users

...