Suragch
Suragch

Reputation: 512446

How to test a Flutter widget's intrinsic size

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.

Upvotes: 5

Views: 3556

Answers (1)

Suragch
Suragch

Reputation: 512446

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.

Upvotes: 18

Related Questions