如何使标签位置在中心屏幕在ListView?



我在flutter中创建了一个自定义标签栏,我想将用户点击的每个标签放在中心,我一直在尝试这样做,但找不到结果

GlobalKey key = gkey[i];

RenderBox box = key.currentContext?.findRenderObject() as RenderBox;
double tabWidth = box.size.width;

ScrollController scroll = _categoryScrollController;
double maxScroll = scroll.position.maxScrollExtent;
double currentScroll = scroll.position.pixels;

double screenWidth = Get.width;
double pos = 0; // help me find the result
// scroll tab to center
_categoryScrollController.animateTo(pos < 0 ? 0 : pos > maxScroll ? maxScroll : pos, duration: Duration(milliseconds: 250), curve: Curves.ease);

在我尝试了几次之后,我找到了结果

GlobalKey key = gkey[i];

RenderBox box = key.currentContext?.findRenderObject() as RenderBox;
double tabWidth = box.size.width;
double tabPosition = box.localToGlobal(Offset.zero).dx;

ScrollController scroll = _categoryScrollController;
double maxScroll = scroll.position.maxScrollExtent;
double currentScroll = scroll.position.pixels;

double screenWidth = Get.width;
double pos = (currentScroll + tabPosition) - (screenWidth / 2) + (tabWidth / 2);
_categoryScrollController.animateTo(pos < 0 ? 0 : pos > maxScroll ? maxScroll : pos, duration: Duration(milliseconds: 250), curve: Curves.ease);

最新更新