Truncate text to a specific digit Flutter Text widget

Follow below step

Step 1: Add DescriptionTextWidget

import 'package:flutter/material.dart';

class DescriptionTextWidget extends StatefulWidget {
  final String text;

  DescriptionTextWidget({this.text});

  @override
  _DescriptionTextWidgetState createState() => _DescriptionTextWidgetState();
}

class _DescriptionTextWidgetState extends State<DescriptionTextWidget>
    with TickerProviderStateMixin<DescriptionTextWidget> {
  bool isExpanded = false;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return new Column(children: <Widget>[
      AnimatedSize(
          vsync: this,
          duration: const Duration(milliseconds: 500),
          child: InkWell(
            onTap: () {
              setState(() {
                isExpanded = !isExpanded;
              });
            },
            child: Container(
              child: RichText(
                text: TextSpan(
                  style: Theme.of(context).textTheme.body1,
                  children: [
                    TextSpan(
                        text: isExpanded
                            ? widget.text
                            : ((widget.text.length > 350)
                                ? widget.text.substring(0, 350)
                                : widget.text),
                       ),
                    WidgetSpan(
                      alignment: PlaceholderAlignment.top,
                      child: (widget.text.length > 150)
                          ? Icon(
                              isExpanded
                                  ? Icons.keyboard_arrow_up
                                  : Icons.keyboard_arrow_down,
                              color: FFB1B1BD,
                              size: 25,
                            )
                          : Container(
                              width: 0,
                              height: 0,
                            ),
                    )
                  ],
                ),
              ),
            ),
          ))
    ]);
  }
}

Step 2: Use

 DescriptionTextWidget(
        text:
            "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.",
      )

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top