如何测试Flutter小部件的固有大小 [英] How to test a Flutter widget's intrinsic size
本文介绍了如何测试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源代码中找到了答案,因此我将其作为Q& A对发布.我的答案在下面.
推荐答案
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. OtherwisegetSize
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屋!
查看全文