Flutter使用PageController控制PageView触发positions.isNotEmpty报错如何解决
报错原因
你遇到的PageController.page cannot be accessed before a PageView is built with it报错,本质是你声明的PageController没有和PageView组件绑定,调用nextPage方法时控制器找不到关联的PageView实例,触发了框架的断言校验。
修复方案
仅需要1处核心修改:给PageView.builder补充controller参数,绑定你声明的boardController即可解决问题。
同时建议做2项优化避免后续出现其他问题:
- 将当前的
StatelessWidget改为StatefulWidget,把PageController放在State类中管理,在dispose生命周期中销毁控制器释放资源 - 点击翻页前判断是否已经到达最后一页,避免无效调用
修复后完整代码
// 改为StatefulWidget方便管理控制器生命周期 class OnBoarding extends StatefulWidget { const OnBoarding({super.key}); @override State<OnBoarding> createState() => _OnBoardingState(); } class _OnBoardingState extends State<OnBoarding> { final List<BoardingModel> boarding = [ BoardingModel( image: 'assets/images/onbording1.png', title: 'Screen title 1', body: 'Screen body 1', ), BoardingModel( image: 'assets/images/onbording1.png', title: 'Screen title 2', body: 'Screen body 2', ), BoardingModel( image: 'assets/images/onbording1.png', title: 'Screen title 3', body: 'Screen body 3', ), ]; final PageController boardController = PageController(); @override void dispose() { // 页面销毁时释放控制器资源 boardController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: Padding( padding: const EdgeInsets.all(23.0), child: Column( children: [ Expanded( child: PageView.builder( // 核心修改:绑定声明好的PageController controller: boardController, physics: const BouncingScrollPhysics(), itemBuilder: (context, index) => buildBoardingItem(boarding[index]), itemCount: boarding.length, ), ), const SizedBox( height: 40.0, ), Row( children: [ const Text('indicator'), const Spacer(), FloatingActionButton( onPressed: () { // 优化:判断未到最后一页再执行翻页 if (boardController.page == boarding.length - 1) { // 到达最后一页时可自定义跳转逻辑 return; } boardController.nextPage( duration: const Duration( milliseconds: 750, ), curve: Curves.fastLinearToSlowEaseIn, ); }, child: const Icon( Icons.arrow_forward_ios, ), ), ], ), ], ), ), ); } // 原有Boarding项构建逻辑保持不变即可 Widget buildBoardingItem(BoardingModel model) { return Column( children: [ Expanded(child: Image.asset(model.image)), const SizedBox(height: 20), Text(model.title, style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold)), const SizedBox(height: 16), Text(model.body, style: const TextStyle(fontSize: 16, color: Colors.grey)), ], ); } } // BoardingModel定义保持你的原有逻辑即可,以下为示例 class BoardingModel { final String image; final String title; final String body; BoardingModel({ required this.image, required this.title, required this.body, }); }
内容的提问来源于stack exchange,提问作者Iliass20
相关产品推荐
相关产品推荐

