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
相关产品推荐
相关产品推荐

