Flutter context.findRenderObject() returns null

Viewed 2929

I am trying to do some Gesture motion logic based on the size of a widget.

To get the size, I am calling the following code in the build method...

final RenderBox renderBox = context.findRenderObject();

This is sometimes returning null?

What is causing this to return null? Is there a more reliable way to get the size of a Widget?

2 Answers

You need to make sure the widget is currently being rendered (for example, on screen) or give it a time to render before trying to access it, for example, by calling this on your initState() if this is from a Stateful Widget:

WidgetsBinding.instance.addPostFrameCallback(() {
   final RenderBox renderBox = context.findRenderObject();
});
RenderBox? _initializedRenderBox;
@override
  void initState() {
    super.initState();
    WidgetsBinding.instance?.addPostFrameCallback((_) {
      _initializedRenderBox = context.findRenderObject() as RenderBox?;
      setState(() {});
    });
  }

You can use an instance variable to assign the RenderBox and use it later in the build function.

Note that call setState to make the call of build again after getting the _initializedRenderBox.

Related