Flutter Markdown "Show more" button

Viewed 1888

I use MarkdownBody from flutter_markdown inside a LimitedBox. When pressing a "Show more" button the maxHeight is set to double.infinity and the full text is shown:

                                             LimitedBox(
                                                maxHeight:
                                                    showMoreCommentsIds
                                                            .contains(
                                                                commentId)
                                                        ? double.infinity
                                                        : 100,
                                                child: Wrap(
                                                  direction:
                                                      Axis.horizontal,
                                                  children: <Widget>[
                                                    MarkdownBody(
                                                      data: showList[index]
                                                          .comment
                                                          .comment,
                                                    )
                                                  ],
                                                ),
                                              ),

But how can I find out the height of the text and only display the "Show more" button, if it is necessary?

2 Answers

You can find the length of the text using text.length and based on that information determine if the "Show more" button is needed. For example:

if(text.length > 60) {
_showButton();
}

You may need to do a little testing with the length of text in order to find out which length you want as the threshold. I just chose 60 as an arbitrary number.

I struggled a little bit with a similar problem because I had to know the size of a widget to apply some logic.

I learned that you can prerender the widget in an Offstage widget, determine it's size with the widget key once it is mounted. You should wait for the rebuild, so you can force it and then you get the size with a function like this:

Future.delayed(Duration(milliseconds:100)).then(
    final widgetSize = getWidgetSize(widgetKey);

    // You can make logic here to remove the Offstage, variables, and free its space.

    // Todo: apply the size in your code after this
)

...

Size getWidgetSize(GlobalKey key) {
  final RenderBox renderBox = key.currentContext.findRenderObject();
  return renderBox.size;
}

In my case, I needed it after tapping somewhere, so I used it inside a function, but maybe you will apply it directly on the initState(), inside a post frame callback.

initState(){
     super.initState();
     ServicesBinding.instance.addPostFrameCallback((_) async {
        // here
     });
}
Related