[英]Getting the position of a widget in a Flutter test?
How do you get the position of a Widget in a Flutter test? 如何在Flutter测试中获取小部件的位置? Ideally the center of the widget, but the top left coordinate would be fine too. 理想情况下,小部件的中心,但左上角的坐标也可以。
This is my test and attempt at a function that finds the location of a Widget on screen. 这是我的测试,并尝试使用一种功能来找到屏幕上小部件的位置。
testWidgets('Pin is in center of screen', (WidgetTester tester) async {
await _setUp(tester); // Does setup
final findPin = find.byKey('pin');
final pinLocation = _getLocation(findPin.evaluate().first);
print(ui.window.physicalSize);
expect(pinLocation.dx, 1200.0);
expect(pinLocation.dy, 900.0);
});
Offset _getLocation(Element element) {
return (element.findRenderObject() as RenderBox).localToGlobal(Offset.zero);
}
The printing for ui.window.physicalSize
(where ui
is the dart:ui
package) tells me the size is Size(2400.0, 1800.0)
. ui.window.physicalSize
(其中ui
是dart:ui
软件包)的打印显示大小为Size(2400.0, 1800.0)
。 However, when I set those midpoints in my test, my test fails, saying that the Size is actually 395.0 and 305.0. 但是,当我在测试中设置这些中点时,测试失败,并说“大小”实际上是395.0和305.0。 My widget is only 30.0 x 30.0 in size, and even 395 +/- 30 doesn't equate anything in the 1200 range. 我的小部件只有30.0 x 30.0大小,甚至395 +/- 30也不等于1200范围内的任何值。
In my test, I then wrapped my widget inside a Container of predefined width (400) and height (300), which is not how it looks in the real app, but for the purposes of testing it's much closer - giving a "center" of 195 and 155, when it should be 200 and 150. 在测试中,我然后将小部件包装在预先定义的宽度(400)和高度(300)的容器中,这与实际应用中的外观不同,但是为了进行测试,它更接近-提供“中心”分别为195和155,则应分别为200和150。
The widget I'm testing (in the code, not with the extra Container in my testWidgets) is approximately: 我正在测试的小部件(在代码中,而不是在我的testWidgets中带有额外的Container)大约是:
return Center(
child: Container(
key: Key('pin'),
height: 30.0,
width: 30.0,
color: Colors.pink,
),
);
WidgetTester
具有您要寻找的方法,例如:
tester.getCenter(findPin);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.