Getting the position of a widget in a Flutter test?

3,500

WidgetTester has the methods you are looking for, e.g.:

tester.getCenter(findPin);
Share:
3,500
Mary
Author by

Mary

Updated on November 26, 2022

Comments

  • Mary
    Mary over 1 year

    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,
       ),
    );
    
  • Mary
    Mary over 5 years
    I have no idea why but thought that only the bolded methods in the docs were available. Thanks! I tried this (specifically, used findPin.at(0)) and got an almost-correct center of 210 when I wrapped my widget around the 400x300 Container. I would've expected the center to be 200. I'll do some more fiddling around. However, when removing that Container (because my real app doesn't have it), I still get a dx of 410 (as opposed to ~1200).
  • Bondolin
    Bondolin over 3 years
    Hello @Mary, welcome to Stack Overflow! If you found this answer to be helpful, please use the check icon to mark it as the solution. This will make it easier for folks to see that it works before looking somewhere else, and you get reputation points ;-)