How to test a Flutter widget's intrinsic size

巧了我就是萌 提交于 2019-12-24 22:36:03

问题


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?

I'm not trying to limit the screen size as in this question.

I found the answer in the Flutter source code, so I am posting this as a Q&A pair. My answer is below.


回答1:


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));
  });
}

Notes:

  • 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.


来源:https://stackoverflow.com/questions/59043177/how-to-test-a-flutter-widgets-intrinsic-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!