Technology Sharing

Flutter's custom encapsulation implements splicing at the end of the text... ExpandableText that expands/collapses

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Preface

Recently, I have been busy writing Flutter to adapt to cross-end, complete a common set of codes for Android, iOS, and HarmonyOS, and reduce the cost of human maintenance. In the project, I encountered the need to implement the same as the previous Android native, when a paragraph of text exceeds the maximum number of lines, it is truncated at the end and spliced ​​to expand/collapse. At first, I was not familiar with it, so I used Stack to dynamically control maxLines and overflow, and covered a mask and text in the lower right corner to achieve it. Later, I found that some screen phones would have a part of the text covered and half of the word would be leaked. Today, I finally have time to optimize the implementation plan.

Implementation Code

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

class ExpandableText extends StatefulWidget {
  final String text;
  final int maxLines;
  final TextStyle textStyle;
  final String linkTextExpand;
  final String linkTextCollapse;
  final Color linkTextColor;

  const ExpandableText(
      {super.key,
      required this.text,
      this.maxLines = 2,
      this.textStyle = const TextStyle(color: Colors.black),
      this.linkTextColor = Colors.blue,
      this.linkTextExpand = " 展开",
      this.linkTextCollapse = " 收起"});

  
  State<StatefulWidget> createState() => _ExpandableTextState();
}

class _ExpandableTextState extends State<ExpandableText> {
  bool isExpanded = false;
  late TextSpan expandSpan;
  late TextSpan linkTextSpan;

  
  void initState() {
    super.initState();
    expandSpan = TextSpan(
      text: widget.linkTextExpand,
      style: TextStyle(color: widget.linkTextColor),
      recognizer: TapGestureRecognizer()
        ..onTap = () {
          setState(() {
            isExpanded = !isExpanded;
          });
        },
    );

    linkTextSpan = TextSpan(
      text: '...',
      style: widget.textStyle,
      children: [expandSpan],
    );
  }

  /// 检查文本是否溢出
  bool checkOverflow(double width) {
    final textPainter = TextPainter(
      text: TextSpan(text: widget.text, style: widget.textStyle),
      textDirection: TextDirection.ltr,
    );
    textPainter.layout(maxWidth: width);
    return textPainter.height > widget.maxLines * textPainter.preferredLineHeight;
  }

  
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        final maxWidth = constraints.maxWidth;
        final textSpan = TextSpan(
          text: widget.text,
          style: widget.textStyle,
        );

        final textPainter = TextPainter(
          text: textSpan,
          maxLines: isExpanded ? null : widget.maxLines,
          textDirection: TextDirection.ltr,
        );
        textPainter.layout(maxWidth: maxWidth);

        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            isExpanded ? _buildExpandedText() : _buildCollapsedText(textPainter, maxWidth),
          ],
        );
      },
    );
  }

  /// 构建折叠状态下的文本
  Widget _buildCollapsedText(TextPainter textPainter, double maxWidth) {
    var truncatedText = widget.text;
    if (checkOverflow(maxWidth)) {
      // 文本的长度超过了最大行数,需要截取然后拼接展开部分的逻辑
      final linkPainter = TextPainter(
        text: linkTextSpan,
        textDirection: TextDirection.ltr,
      );
      linkPainter.layout(maxWidth: maxWidth);
      final position = textPainter.getPositionForOffset(Offset(maxWidth - linkPainter.width, textPainter.height));
      final endOffset = textPainter.getOffsetBefore(position.offset) ?? position.offset;
      truncatedText = widget.text.substring(0, endOffset);
    }

    return RichText(
      text: TextSpan(
        text: truncatedText,
        style: widget.textStyle,
        children: widget.text.length == truncatedText.length ? [] : [linkTextSpan],
      ),
      maxLines: widget.maxLines,
      overflow: TextOverflow.ellipsis,
    );
  }

  /// 构建展开状态下的文本
  Widget _buildExpandedText() {
    final collapseSpan = TextSpan(
      text: widget.linkTextCollapse,
      style: TextStyle(color: widget.linkTextColor),
      recognizer: TapGestureRecognizer()
        ..onTap = () {
          setState(() {
            isExpanded = !isExpanded;
          });
        },
    );

    return RichText(
      text: TextSpan(
        text: widget.text,
        style: widget.textStyle,
        children: [collapseSpan],
      ),
    );
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135

Functional Overview

ExpandableText is a custom Flutter widget for displaying long text content. When the text length exceeds the preset maximum number of lines, the text will be collapsed and an "Expand" link will be displayed. Click it to fully expand the text, and click it again to collapse the text.

Key implementation points

1. State management:

Use StatefulWidget and _ExpandableTextState to manage the expanded/collapsed state of the text.
The isExpanded variable controls the display state of the text.

2. Text processing:

Use the TextPainter and RichText components to measure and render text.
When the text exceeds the maximum number of lines, the text is calculated and truncated to ensure that it is displayed correctly in the collapsed state, and an "expand" link is added.

3. Interaction logic:

Add click event listening through TapGestureRecognizer to implement the "expand" and "collapse" functions.
The setState method is used to update the display state of the text.

4. Responsive Layout:

Use LayoutBuilder to get the available width to adapt to different screen sizes and layout environments.
The checkOverflow method is used to determine whether the text exceeds the maximum number of lines set.

5. Style customization:

Provides multiple configurable parameters, such as maxLines, textStyle, linkTextExpand, linkTextCollapse, linkTextColor, allowing users to customize the appearance and behavior of text.

6. How to use

ExpandableText(
  text: "这是一段很长的文本,它将被折叠起来,只有在点击'展开'链接后才会完全显示。",
  maxLines: 2,
  textStyle: TextStyle(fontSize: 16, color: Colors.black),
  linkTextExpand: " 展开",
  linkTextCollapse: " 收起",
  linkTextColor: Colors.blue,
);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

Precautions

Make sure when using ExpandableText that you provide enough context width so that the text's collapse point is calculated correctly.
Custom style parameters should be adjusted according to actual needs to achieve the best visual effect.