Flutter cast RenderObject to RenderBox
Asked Answered
N

4

8

I am trying to follow this tutorial creating a DropDown. But I can not copy his code because Flutter 2.0 is forbidding it because of these lines:

  void findDropdownData() {
    RenderBox renderBox = actionKey.currentContext!.findRenderObject()!;
    height = renderBox.size.height;
    width = renderBox.size.width;
    Offset? offset = renderBox.localToGlobal(Offset.zero);
    xPosition = offset!.dx;
    yPosition = offset.dy;
  }

As you can see I tried do add some ! and ? but it is still not working. The main issue is that findRenderObject returns RenderObject but I need it to be a RenderBox... Any idea what's wrong here? Can not figure it out..

Nkvd answered 11/4, 2021 at 13:18 Comment(0)
N
23

The solution was easier than I thought:

simply use as like this:

RenderBox renderBox =
    actionKey.currentContext!.findRenderObject()! as RenderBox;
Nkvd answered 11/4, 2021 at 13:31 Comment(0)
R
2

Sometimes actionkey may shows error, so simply use as

RenderBox renderBox = context.findRenderObject()! as RenderBox;
Rubadub answered 29/8, 2021 at 4:26 Comment(0)
C
0

u can also add more safety check, based on @Chris's

    RenderObject? obj = context.findRenderObject();
    if (obj == null) {
        return;
    }
    bool isBox = obj is RenderBox;
    if (isBox == false) {
        return;
    }
    RenderBox box = obj as RenderBox;
Chockfull answered 24/6, 2022 at 21:38 Comment(0)
C
0

You can also resolve it like this

final renderBox = actionKey.currentContext!.findRenderObject()! as RenderBox;
Cyprinid answered 27/12, 2022 at 9:19 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Dincolo

© 2022 - 2024 — McMap. All rights reserved.