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

Flutter多按钮跳转应用开发中MyApp类context未定义报错如何解决

错误原因

你自定义的FirstButton、SecondButton等按钮方法属于MyApp类的成员方法,方法内部没有接收BuildContext类型的入参,而build方法中的context是局部变量,无法被类的其他成员方法直接访问,因此抛出了context未定义的错误。

解决方案

方案一:给按钮方法传递context参数(修改成本最低)

  1. 修改所有按钮方法的定义,新增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,
        ),
      ),
    ),
  );
}
  1. 在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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 20:15:04