Flutter - get RenderBox position after setState changes its position

Viewed 226

I'm geting Container position and I do some logic with scroll listener reacting to the position. This is how I grab the position:

  void _getOffset() {
    RenderBox box = _filterKey.currentContext!.findRenderObject() as RenderBox;
    Offset position = box.localToGlobal(Offset.zero);
    _filterButtonsPosition = position.dy;
    print(widget._scrollController.offset);
    print(_filterButtonsPosition);
  }

I run this function in initState like this:

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
      _getOffset();
    });
  }

At this point everything works fine.

However, it is possible that the position of the Container might change. This may happen when user opens accordion that I have on the page. I'm able to catch that event with

   NotificationListener<SizeChangedLayoutNotification>(
                  onNotification: (SizeChangedLayoutNotification notification) { 
                     WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
                      _getOffset();
                     });
                    return true;
                  },
                  child: SizeChangedLayoutNotifier(
                    child: ContainerThatChangeSizeOnPressed()

Here's the problem. _getOffset() won't calculate position properly. It points to the end of the window. My guess is that flutter calculates it before the page is fully rendered. How can I solve this?

0 Answers
Related