在 Flutter 中,TextPainter 的 layout 方法只能计算纯文本的宽度,无法计算包含 WidgetSpan 的 TextSpan 的宽度。如果想要在不绘制的时候得到 WidgetSpan 的宽度,可以通过以下方法实现:

  1. 创建一个空的 CustomPaint 对象,并将 TextSpan 作为其 child,然后调用 CustomPaint 的 size 属性来获取 TextSpan 的宽度。

  2. 使用 LayoutBuilder 包装 TextSpan,并在回调方法中获取其宽度。

示例代码如下:

  1. 使用 CustomPaint 获取 TextSpan 的宽度
CustomPaint(
  painter: _TextSpanPainter(textSpan),
  child: Container(),
);

class _TextSpanPainter extends CustomPainter {
  final TextSpan textSpan;

  _TextSpanPainter(this.textSpan);

  @override
  void paint(Canvas canvas, Size size) {}

  @override
  bool shouldRepaint(_TextSpanPainter oldDelegate) => false;

  @override
  bool shouldRebuildSemantics(_TextSpanPainter oldDelegate) => false;

  @override
  Size get size => textSpan?.layout(const TextPainter(
    textDirection: TextDirection.ltr,
    textScaleFactor: 1.0,
  ))?.size ?? Size.zero;
}
  1. 使用 LayoutBuilder 获取 TextSpan 的宽度
LayoutBuilder(
  builder: (BuildContext context, BoxConstraints constraints) {
    final textPainter = TextPainter(
      text: textSpan,
      textDirection: TextDirection.ltr,
      textScaleFactor: MediaQuery.of(context).textScaleFactor,
    )..layout(maxWidth: constraints.maxWidth);
    return SizedBox(
      width: textPainter.width,
      height: textPainter.height,
      child: Text.rich(textSpan),
    );
  },
);
Flutter 中计算包含 WidgetSpan 的 TextSpan 宽度

原文地址: https://www.cveoy.top/t/topic/jAxX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录