Flutter: How to hide or show more text within certain length

前端 未结 7 929
小鲜肉
小鲜肉 2020-11-29 07:00

My Container having a description about movies.

Initially i want to show only few lines of description. And below to that there should be a link (more...

相关标签:
7条回答
  • 2020-11-29 07:28
    Widget _text() {
    var exceeded;
    return LayoutBuilder(builder: (context, size) {
      // Build the textspan
      var span = TextSpan(
        text:
            "The red-tailed tropicbird is a seabird native to the tropical Indian and Pacific Oceans. One of three closely related species of tropicbird, it has four subspecies. Text wrapping is quite a pain for me too. I find that putting Text in a Container and then wrapping that container in a Expanded/Flexible works well.",
        style: Theme.of(context).textTheme.body1.copyWith(color: Colors.white),
      );
    
      // Use a textpainter to determine if it will exceed max lines
      var tp = TextPainter(
        maxLines: _maxLine.toInt(),
        textAlign: TextAlign.left,
        textDirection: TextDirection.ltr,
        text: span,
      );
    
      // trigger it to layout
      tp.layout(maxWidth: size.maxWidth);
    
      // whether the text overflowed or not
      exceeded = tp.didExceedMaxLines;
    
      // return Column(children: <Widget>[
      return Container(
        child: exceeded && seeMoreClicked
            ? _seeMoreLess(span, "See Less ")
            : exceeded && !seeMoreClicked
                ? _seeMoreLess(span, "See More", 3)
                : Text.rich(
                    span,
                    overflow: TextOverflow.visible,
                  ),
      );
    });
    }
    
    Widget _seeMoreLess(TextSpan span, String _text, [int maxLine = 0]) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.end,
      children: <Widget>[
        maxLine > 0
            ? Text.rich(
                span,
                overflow: TextOverflow.ellipsis,
                maxLines: 3,
              )
            : Text.rich(
                span,
                overflow: TextOverflow.visible,
              ),
        InkWell(
            child: Text(
              _text,
              style: Theme.of(context)
                  .textTheme
                  .body1
                  .copyWith(color: Colors.blue),
            ),
            onTap: () {
              setState(() {
                seeMoreClicked = !seeMoreClicked;
              });
            }),
      ],
    );
    
    0 讨论(0)
提交回复
热议问题