[英]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.我在 Flutter 源代码中找到了答案,所以我将其作为问答对发布。 My answer is below.我的回答如下。
The WidgetTester
has a getSize
method on it that you can use to get the rendered size of the widget. WidgetTester
有一个getSize
方法,您可以使用它来获取小部件的渲染大小。
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:笔记:
Center
widget makes it wrap the content.将自定义小部件放在Center
小部件中使其包装内容。 Otherwise getSize
would get the screen size.否则getSize
将获得屏幕尺寸。MongolRichText
is vertical text), so I updated the test with the expected numbers to make the test pass.它们看起来很合理( MongolRichText
是垂直文本),所以我用预期的数字更新了测试以使测试通过。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.