You need to enable JavaScript to run this app. Flutter打字动画场景下计算嵌套TextSpan所有文本长度总和方案咨询
优惠活动
大模型
产品
解决方案
定价
更多

Flutter打字动画场景下计算嵌套TextSpan所有文本长度总和方案咨询

Flutter 嵌套TextSpan打字机动效组件解决方案

核心问题

原有打字机动效组件仅支持根节点带文本的单层TextSpan,遇到嵌套TextSpan时会因为父节点text、style为null触发空异常,且无法正确统计所有子文本总长度,同时原有逻辑未做文本裁剪,打字机逐字显示效果实际不生效。

实现思路

新增三个递归工具方法,遍历整个TextSpan树结构:

  1. 递归累加所有节点text属性的长度,得到总文本长度
  2. 递归遍历找到最后一个携带text属性的TextSpan,获取其style属性
  3. 递归裁剪TextSpan到当前动画进度对应的字符长度,实现逐字显示效果

完整修改后代码

// @dart=2.9
import 'package:flutter/material.dart';

// ignore: must_be_immutable
class TypeWriterAnimatedText extends StatefulWidget {
  final TextSpan textSpan;
  TypeWriterAnimatedText({Key key, @required this.textSpan}) : super(key: key);

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

class _TypeWriterAnimatedTextState extends State<TypeWriterAnimatedText> with TickerProviderStateMixin {
  Animation<double> _textBlinkCursorAnimation;
  Animation<double> _textBlinkCursorAnimationCurve;
  AnimationController _textBlinkCursorAnimationController;
  
  bool _blink = true;
  // 缓存计算结果,避免重复递归损耗性能
  int _totalTextLength;
  TextStyle _lastTextStyle;

  // 递归计算TextSpan树的总文本长度
  int _calculateTotalLength(TextSpan span) {
    int length = span.text?.length ?? 0;
    if (span.children != null) {
      for (var child in span.children) {
        if (child is TextSpan) {
          length += _calculateTotalLength(child);
        }
      }
    }
    return length;
  }

  // 递归获取最后一个带文本的TextSpan的style
  TextStyle _getLastTextStyle(TextSpan span) {
    // 优先倒序遍历子节点,找最后一个有文本的子节点
    if (span.children != null) {
      for (int i = span.children.length - 1; i >= 0; i--) {
        var child = span.children[i];
        if (child is TextSpan) {
          final childStyle = _getLastTextStyle(child);
          if (childStyle != null) return childStyle;
        }
      }
    }
    // 当前节点有文本就返回自身style
    if (span.text != null && span.text.isNotEmpty) {
      return span.style;
    }
    return null;
  }

  // 递归裁剪TextSpan到指定字符长度
  TextSpan _cropTextSpan(TextSpan span, int remainingLength) {
    if (remainingLength <= 0) return const TextSpan();
    // 先处理当前节点的文本
    String currentText = span.text ?? '';
    if (currentText.length > remainingLength) {
      return TextSpan(
        text: currentText.substring(0, remainingLength),
        style: span.style,
      );
    }
    remainingLength -= currentText.length;
    List<TextSpan> croppedChildren = [];
    if (span.children != null) {
      for (var child in span.children) {
        if (child is TextSpan && remainingLength > 0) {
          final croppedChild = _cropTextSpan(child, remainingLength);
          croppedChildren.add(croppedChild);
          remainingLength -= _calculateTotalLength(croppedChild);
        } else {
          break;
        }
      }
    }
    return TextSpan(
      text: currentText,
      style: span.style,
      children: croppedChildren,
    );
  }

  @override
  void initState() {
    super.initState();
    // 初始化时提前计算好总长度和最后一个style,避免重复计算
    _totalTextLength = _calculateTotalLength(widget.textSpan);
    _lastTextStyle = _getLastTextStyle(widget.textSpan) ?? DefaultTextStyle.of(context).style;
    // 光标动画逻辑保持不变
    _textBlinkCursorAnimationController =
        AnimationController(vsync: this, duration: Duration(milliseconds: 200));
    _textBlinkCursorAnimationCurve = CurvedAnimation(
        parent: _textBlinkCursorAnimationController,
        curve: Curves.easeInOutQuart,
        reverseCurve: Curves.linear);
    _textBlinkCursorAnimation = Tween<double>(begin: 0, end: 1)
        .animate(_textBlinkCursorAnimationCurve)
      ..addListener(() {
        setState(() {});
      })
      ..addStatusListener((status) {
        if (status == AnimationStatus.completed && _blink == true) {
          _textBlinkCursorAnimationController.reverse();
        } else if (status == AnimationStatus.dismissed && _blink == true) {
          _textBlinkCursorAnimationController.forward();
        }
      });
    _textBlinkCursorAnimationController.forward();
  }

  @override
  void dispose() {
    _textBlinkCursorAnimationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 100,
      child: TweenAnimationBuilder<int>(
        tween: IntTween(begin: 0, end: _totalTextLength),
        builder: (BuildContext context, int value, Widget child){
          WidgetsBinding.instance.addPostFrameCallback((_){
            if(value == _totalTextLength){
              Future.delayed(const Duration(milliseconds: 1800)).then((_){
                if(mounted) {
                  setState(() {
                    _blink = false;
                    _textBlinkCursorAnimationController.reset();
                  });
                }
              });
            }
          });
          return SelectableText.rich(
            TextSpan(
                children: [
                  _cropTextSpan(widget.textSpan, value),
                  TextSpan(
                    text: _blink == false ? '' : '_',
                    style: _lastTextStyle.copyWith(color: _lastTextStyle.color.withOpacity(_textBlinkCursorAnimation.value)),
                  ),
                ]),
          );
        },
        duration: const Duration(seconds: 2),
      ),
    );
  }
}

适配说明

  1. 支持任意层级嵌套的TextSpan结构,自动累加所有子节点文本长度
  2. 自动适配最后一段文本的样式作为光标样式,无自定义style时会自动继承父级默认文本样式
  3. 新增文本裁剪逻辑,打字机逐字显示效果正常
  4. 新增mounted判断,避免组件销毁后调用setState触发异常

内容的提问来源于stack exchange,提问作者Seyit Gokce

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 19:27:07