Search code examples
flutterlayout

Flutter - HIde text that overflow from the Container with dynamic height


So I have a container whose height depends on the screen size of the device. And I've some text in that container. I want the container to contain all the text it can, but hide the one that starts to overflow. Something like below: enter image description here

But I can't really figure this out. I do have a code, but in my current code, I need to specify max lines to be able to hide the rest of the overflow. But as the container height is going to be dynamic, I've no idea what the maxLines are going to be in there. So is there any way to achieve this?

Current Code
Container(
                                  height: MediaQuery.of(context).size.height * .3,
                                  color: Colors.red,
                                  child: Text(
                                    'Adipisci placeat ipsum et reiciendis sunt velit. Adipisci placeat ipsum et reiciendis sunt velit. Adipisci placeat ipsum et reiciendis sunt velit. Adipisci placeat ipsum et reiciendis sunt velit. Adipisci placeat ipsum et reiciendis sunt velit. Adipisci placeat ipsum et reiciendis sunt velit. Adipisci placeat ipsum et reiciendis sunt velit.',
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 12,
                                      letterSpacing: .5,
                                      height: 1.3,
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                    maxLines: 4,
                                  ),
                                ),

Solution

  • TextOverflow.ellipsis is good when you know in advance the text max lines; In your case as you want the text to adapt to the container size, you shouldn't use TextOverflow.ellipsis nor maxLines, it will adapt to the container and hide the overflowed text.

    Container(
     height: MediaQuery.of(context).size.height * .3,
     color: Colors.red,
     child: Text(
         'Adipisci placeat ipsum et reiciendis sunt velit. Adipisci placeat ipsum et reiciendis sunt velit. Adipisci placeat ipsum et reiciendis sunt velit. Adipisci placeat ipsum et reiciendis sunt velit. Adipisci placeat ipsum et reiciendis sunt velit. Adipisci placeat ipsum et reiciendis sunt velit. Adipisci placeat ipsum et reiciendis sunt velit.',
         style: TextStyle(
             color: Colors.white,
             fontSize: 12,
             letterSpacing: .5,
             height: 1.3,
         ),
      ),
    )