如何测试 Flutter 小部件的固有大小 [英] How to test a Flutter widget's intrinsic size

查看:19
本文介绍了如何测试 Flutter 小部件的固有大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义文本小部件,我正在尝试测试该小部件对于某些文本字符串是否具有一定的固有大小.

I have a custom text widget and I am trying to test that the widget has a certain intrinsic size for some text string.

void main() {
  testWidgets('MongolRichText has correct size for string', (WidgetTester tester) async {
    await tester.pumpWidget(MongolRichText(text: TextSpan(text: 'hello'),));

    final finder = find.byType(MongolRichText);
    expect(finder, findsOneWidget);

    // How do I check the size?
  });
}

如何检查小部件的固有尺寸?

How do I check the intrinsic size of the widget?

我不想像 这个问题.

我在 Flutter 源代码中找到了答案,因此我将其发布为问答对.我的答案如下.

推荐答案

WidgetTester 上有一个 getSize 方法,您可以使用它来获取渲染后的大小小部件.

The WidgetTester has a getSize method on it that you can use to get the rendered size of the widget.

void main() {
  testWidgets('MongolRichText has correct size for string', (WidgetTester tester) async {
    await tester.pumpWidget(Center(child: MongolText('Hello')));

    MongolRichText text = tester.firstWidget(find.byType(MongolRichText));
    expect(text, isNotNull);

    final Size baseSize = tester.getSize(find.byType(MongolRichText));
    expect(baseSize.width, equals(30.0));
    expect(baseSize.height, equals(150.0));
  });
}

注意事项:

  • 将自定义小部件放在 Center 小部件中,使其包装内容.否则 getSize 会得到屏幕尺寸.
  • 通过运行测试并查看实际值应该是多少,我得到了实际数字.它们看起来很合理(MongolRichText 是垂直文本),所以我用预期的数字更新了测试以使测试通过.
  • 此解决方案改编自 Futter文本小部件测试源代码.
  • Putting the custom widget in a Center widget makes it wrap the content. Otherwise getSize would get the screen size.
  • I got the actual numbers by running the test and seeing what the actual values should be. They seemed reasonable (MongolRichText is vertical text), so I updated the test with the expected numbers to make the test pass.
  • This solution was adapted from the Futter Text widget testing source code.

这篇关于如何测试 Flutter 小部件的固有大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆