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

Flutter页面切换触发断言错误:Failed assertion: child == null || indexOf(child) > index

解决Flutter PageView跳转报错:Failed assertion: child == null || indexOf(child) > index: is not true

问题根源

你的代码里Page2的状态类存在两处复制粘贴遗漏的错误,导致PageView无法正确处理页面切换:

  • Page2的createState方法错误返回了_Page1State,而非对应的_Page2State
  • _Page2State继承的是State<Page1>,而非State<Page2>

这两个错误会让PageView在加载Page2时,实际创建的是Page1的状态实例,导致Widget树结构异常,触发断言检查失败。

修正后的Page2代码

class Page2 extends StatefulWidget {
  final PageController pageController;

  Page2({required this.pageController});

  @override
  _Page2State createState() => _Page2State();
}

class _Page2State extends State<Page2> {
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        children: <Widget>[
          TextFormField(
            decoration: InputDecoration(labelText: 'Name'),
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Please enter your name';
              }
              return null;
            },
          ),
          TextFormField(
            decoration: InputDecoration(labelText: 'Email'),
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Please enter your email';
              }
              return null;
            },
          ),
          ElevatedButton(
            child: Text('Next'),
            onPressed: () {
              if (_formKey.currentState!.validate()) {
                _formKey.currentState!.save();
                // 增加页面边界判断,避免最后一页调用nextPage报错
                if (widget.pageController.page! < 1) {
                  widget.pageController.nextPage(duration: Duration(milliseconds: 300), curve: Curves.ease);
                }
              }
            },
          ),
          ElevatedButton(
            child: Text('Back'),
            onPressed: () {
              widget.pageController.previousPage(duration: Duration(milliseconds: 300), curve: Curves.ease);
            },
          ),
        ],
      ),
    );
  }
}

额外优化建议

在调用nextPage时增加页面边界判断,避免当前处于最后一页时仍尝试跳转,引发新的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 19:25:41