How do you get the position of a Widget in a Flutter test? 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)
. However, when I set those midpoints in my test, my test fails, saying that the Size is actually 395.0 and 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.
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.
The widget I'm testing (in the code, not with the extra Container in my testWidgets) is approximately:
return Center(
child: Container(
key: Key('pin'),
height: 30.0,
width: 30.0,
color: Colors.pink,
),
);
Aucun commentaire:
Enregistrer un commentaire