dart - 导航未定义名称上下文
问题描述
我目前正在查看在我的应用程序中使用不同屏幕进行导航,到目前为止,我可以成功地从LoginScreen导航到EventsScreen。问题是在 EventsScreen 中有一个按钮,如果单击它应该带我到LoginScreen,这就是我拥有的代码。
在我的app.dart文件MaterialApp小部件中,我的路线为
单击假日平面按钮时,它不会将我带到“/HolidayScreen”路线。
如何解决[dart] Undefined name 'context'?
events_screen.dart
import 'package:flutter/material.dart';
import 'holiday.dart';
class EventsScreen extends StatelessWidget {
Widget build(context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.white,
body: Container(
alignment: Alignment.center,
margin: EdgeInsets.all(20.0),
child: ListView(
children: <Widget>[
Container(margin: EdgeInsets.only(bottom: 20.0)),
eventsButton(),
Container(margin: EdgeInsets.only(bottom: 20.0)),
],
),
),
),
);
}
Widget eventsButton() {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
FlatButton(
color: Colors.red[800],
onPressed: () {},
child: Text(
'Events',
style: new TextStyle(color: Colors.white, fontWeight: FontWeight.normal),
),
),
Container(margin: EdgeInsets.only(right: 20.0)),
FlatButton(
color: Colors.red[800],
child: Text(
'Holidays',
style: new TextStyle(color: Colors.white, fontWeight: FontWeight.normal),
),
onPressed: () {
Navigator.pushNamed(context, "/Holiday");
},
),
Container(margin: EdgeInsets.only(right: 20.0)),
FlatButton(
color: Colors.red[800],
onPressed: () {},
child: Text(
'Flights',
style: new TextStyle(color: Colors.white, fontWeight: FontWeight.normal),
),
),
],
);
}
}
解决方案
很简单,只需将 BuildContext 传递给您的eventsButton
方法
Widget build(context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.white,
body: Container(
alignment: Alignment.center,
margin: EdgeInsets.all(20.0),
child: ListView(
children: <Widget>[
Container(margin: EdgeInsets.only(bottom: 20.0)),
eventsButton(context),
Container(margin: EdgeInsets.only(bottom: 20.0)),
],
),
),
),
);
}
并在您的方法中添加一个参数
Widget eventsButton(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment
//...
更新
并改变这个:
Navigator.pushNamed(context, "/Holiday");
对此:
Navigator.pushNamed(context, "/HolidayScreen");
因为您的路线名称是 HolidayScreen 而不是 Holiday
推荐阅读
- microservices - 带有事件驱动编排的 REST API 命令
- javascript - 将 Django FilteredSelectMulitple 实现为无管理表单
- elixir - 监督树中的名称解析
- ios - 是否可以在自定尺寸单元中使用自定尺寸单元?
- javascript - 我需要等待每个嵌套的承诺数组吗?
- ios - 没有使用自动布局的 LayoutConstraints 错误
- xml - SAML AuthN 请求无效
- microsoft-graph-api - 使用 Action.OpenUrl 从自适应卡打开任务模块
- multithreading - 为什么变量绑定会影响循环体内的生命周期?
- java - 所有服务器请求的@Pointcut 不适用于测试上下文