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

