Flutter calling localToGlobal on listview item always return dx= 0.0?

Viewed 26

Hello everybody I have a problem getting the global position of an item inside listview I don't know why the localToGlobal method always return an offset with dx=0.0 my goal is to animate a widget to specific item in listview so I need to know the global position of that target item.


... 
ListView.builder(
            
            itemCount: categoryState.list.length,
            itemBuilder: (ctx, i) {
              return CategoryItem(index:i);
            },
            shrinkWrap: true,
          ),
...

class CategoryItem extends StatefulWidget{
   const CategoryItem ({
    Key? key,
    required this.index});
 @override
  State<CategoryItem> createState() => CategoryItemState();
}
CategoryItemState  extends State<CategoryItem >{
GlobalKey _globalKey = GlobalKey();
@override
  Widget build(BuildContext context) {
    return InkWell(
         key:_globalKey,
         onTap:()=>getPosition(),
        child:Text(widget.index.toString())
     )
}
  Offset? getPosition() {
    RenderBox? object =
        _globalKey.currentContext?.findRenderObject() as RenderBox;
  
      return object.localToGlobal(Offset.zero);//===Always return dx==zero
   
  }
}
1 Answers

dx is always zero because that's the distance between the widget and the left side of the screen. In Flutter, Offset.zero is in the top left of the screen, the x axis increases to the right, and the y axis increases downward.

Related