You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中PageView无法使用builder时如何获取当前页面索引

解决方案

无需替换为PageView.builder,通过状态变量存储当前页索引,配合PageView的内置回调即可拿到准确的页面索引,实现步骤:

  • 在State类中定义整型状态变量currentPageIndex,初始值与PageController的initialPage参数保持一致,设为0
  • 为PageView配置onPageChanged回调,页面切换动画结束后会自动返回当前页的整数索引,在回调中调用setState更新currentPageIndex的值
  • 更新后的currentPageIndex可直接作为入参传给FavoriteCityScreen组件
  • 切记在dispose生命周期中释放PageController,避免内存泄漏

可直接运行的修正代码

class _YourWidgetState extends State<YourWidget> {
  int currentPageIndex = 0;
  final PageController controller = PageController(initialPage: 0);

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => CityData(),
      child: MaterialApp(
        home: PageView(
          controller: controller,
          onPageChanged: (index) {
            setState(() {
              currentPageIndex = index;
            });
          },
          children: [
            HomeBody(),
            FavoriteCityScreen(
              i: currentPageIndex,
            ),
          ],
        ),
      ),
    );
  }
}

特殊场景适配

如果业务需要在滑动过程中实时获取页面偏移值(比如实现滑动联动动画效果),可以通过PageController的监听获取controller.page的浮点值:

@override
void initState() {
  super.initState();
  controller.addListener(() {
    // 滑动过程中该值会实时变化,范围为相邻页索引之间的浮点数
    final double? currentPage = controller.page;
    // 按需编写业务逻辑
  });
}

注意:该监听会在滑动过程中高频触发,非必要不要在监听内直接调用setState刷新整页,避免性能问题。


内容的提问来源于stack exchange,提问作者Adam gh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 04:24:15