Flutter多按钮跳转应用开发中MyApp类context未定义报错如何解决
错误原因
你自定义的FirstButton、SecondButton等按钮方法属于MyApp类的成员方法,方法内部没有接收BuildContext类型的入参,而build方法中的context是局部变量,无法被类的其他成员方法直接访问,因此抛出了context未定义的错误。
解决方案
方案一:给按钮方法传递context参数(修改成本最低)
- 修改所有按钮方法的定义,新增
BuildContext context作为入参,以FirstButton为例,其余三个按钮按照相同规则修改即可:
// 新增context参数 Widget FirstButton(double width, BuildContext context) { return Expanded( child: SizedBox( width: width - 20, child: RaisedButton( onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) => LectureVideo())); }, color: Colors.red, child: Text( "Lecture Video", textScaleFactor: 2.0, ), ), ), ); }
- 在
build方法调用按钮组件时,将当前的context传入:
children: [ Container(margin: EdgeInsets.only(bottom: 20.0)), FirstButton(width, context), Container(margin: EdgeInsets.only(bottom: 20.0)), SecondButton(width, context), Container(margin: EdgeInsets.only(bottom: 20.0)), ThirdButton(width, context), Container(margin: EdgeInsets.only(bottom: 20.0)), FourthButton(width, context), Container(margin: EdgeInsets.only(bottom: 20.0)), ],
可选优化建议
目前代码中使用的RaisedButton已经在新版本Flutter中被弃用,建议替换为ElevatedButton,用法基本一致,只需要修改组件名即可。
内容的提问来源于stack exchange,提问作者Pencen
相关产品推荐
相关产品推荐

