您可以使用TextPainter来计算WidgetSpan的宽度。以下是一个示例代码:

final text = 'Hello World';
final widget = Container(
  padding: EdgeInsets.all(4),
  decoration: BoxDecoration(
    color: Colors.blue,
    borderRadius: BorderRadius.circular(4),
  ),
  child: Text('WidgetSpan'),
);
final span = WidgetSpan(child: widget);

final textSpan = TextSpan(text: text, children: [span]);
final textStyle = TextStyle(fontSize: 16);
final textPainter = TextPainter(text: textSpan, textDirection: TextDirection.ltr, maxLines: 1)
  ..layout(minWidth: 0, maxWidth: double.infinity);
final widgetSpanWidth = textPainter.widthOfSpan(textSpan.children.indexOf(span), textStyle);

在这个示例中,我们首先创建了一个包含WidgetSpanTextSpan,然后使用TextPainter来计算WidgetSpan的宽度。我们使用TextPainter.widthOfSpan()方法来获取WidgetSpan的宽度。注意,我们需要指定TextPaintermaxWidthdouble.infinity,以便它可以计算出整个文本的宽度。

Flutter 获取 WidgetSpan 宽度,无需绘制

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

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