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

Flutter页面跳转时报Undefined name 'context'等错误如何解决

报错原因及修复方案

报错1:Undefined name 'context'

你自定义的NeighbourhoodListTile直接继承ListTile,在构造方法的初始化列表中定义onTap回调时,该作用域下没有可访问的context变量,上层传入的BuildContext并没有传递到这个类中,所以无法识别。

报错2:Undefined name 'neigh1'

neigh1是目标页面NeighbourhoodAdmiralty定义的接收参数的形参名,不是你要传入的实际值,你需要传入当前点击的社区名称作为实参。


最简修复代码

直接移除单独的NeighbourhoodListTile类,在ListView.builder的itemBuilder中直接构造列表项,即可同时解决两个问题,修改后的neighbourhoodlist.dart完整代码如下:

import 'package:flutter/material.dart';
import 'indv_neighbourhoods/neighbourhoodlist_admirality.dart';

class NeighbourhoodList extends StatefulWidget {
  NeighbourhoodList({ this.name = "name"});
  final String name;

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

class _NeighbourhoodListState extends State<NeighbourhoodList> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          'Neighbourhoods',
        ),
      ),
      body: _buildListView(context),
    );
  }

  ListView _buildListView(BuildContext context){
    return ListView.builder(
      itemCount: allNeighbourhoods.length,
      itemBuilder: (BuildContext context, int index) {
          NeighbourhoodList neighbourhoodlist = allNeighbourhoods[index];
          return ListTile(
            title: Text(neighbourhoodlist.name),
            trailing: Icon(Icons.arrow_forward),
            onTap: (){
              Navigator.push(
                context, 
                // 传入当前点击的社区名称作为实参
                MaterialPageRoute(builder: (context) => NeighbourhoodAdmiralty(neighbourhoodlist.name)),
              );
            }
          );
        });
  }
}

List<NeighbourhoodList> allNeighbourhoods = [
  NeighbourhoodList(name: 'Admiralty'),
  NeighbourhoodList(name: 'Aljunied'),
  NeighbourhoodList(name: 'Ang Mo Kio'),
];

额外优化建议

后续所有社区的详情页可以直接复用同一个页面,不需要每个社区单独新建文件,只需要根据传入的社区名称参数,动态渲染对应内容即可,能大幅减少重复代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 10:00:02