'Why is Position not accurate using GlobalKey in widget

I'm experimenting with GlobalKeys and I'm trying to move a CustomPainter object on top of a generated GridListView, from a grid item to another grid item using their index by adding each of their key in an array of GlobalKeys.

The issue I have is the globalPaintBounds by GlobalKeyExtension (which I have found here, not my code) is giving back an inaccurate position, but the output of the key is consistent. I need help figuring out why this happens.

Thanks!

  List<GlobalKey> keys = [];
  GlobalKey<GridPainterState> _painterKey = GlobalKey<GridPainterState>();
  int originIndex = 0;
  int destinationIndex = 0;
  
  Widget buildGrid() {
      return Stack(
        children: [
          GridView(
              shrinkWrap: true,
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisSpacing: 1,
                mainAxisSpacing: 1,
                crossAxisCount: 8,
              ),
              children: List.generate(160, (index){
                return GestureDetector(
                  onTap: () {
                    setState(() {
                      destinationIndex = userPos;
                      originIndex = index;
                    });
                  },
                  child: Container(
                    key: keys[index],
                    width: double.infinity,
                    height: double.infinity,
                    child: Text($index),
                  ),
                );
              })
          ),
          GridPainter(key: _painterKey, offsetOrigin: key[originIndex].globalPaintBounds, offsetDestination: key[destinationIndex].globalPaintBounds,)
        ],
      );
  }




extension GlobalKeyExtension on GlobalKey {
  Rect? get globalPaintBounds {
    final renderObject = currentContext?.findRenderObject();
    final translation = renderObject?.getTransformTo(null).getTranslation();
    if (translation != null && renderObject?.paintBounds != null) {
      final offset = Offset(translation.x, translation.y);
      return renderObject!.paintBounds.shift(offset);
    } else {
      return null;
    }
  }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source