我需要帮助,我正在尝试按下按钮时显示新页面。我收到以下错误:
I/flutter (31562): The following NoSuchMethodError was thrown while handling a gesture:
I/flutter (31562): Class 'MyHomePage' has no instance getter 'context'.
I/flutter (31562): Receiver: Instance of 'MyHomePage'
I/flutter (31562): Tried calling: context
I/flutter (31562): When the exception was thrown, this was the stack:
这是我的代码:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class MyHomePage extends StatelessWidget{
Container pictureSection(){
return new Container(
child: new Image.asset(
'images/sw.jpeg',
width: 600.0,
height: 240.0,
fit: BoxFit.cover,
),
);
}
Container mainMenuSection(){
var spacer = new SizedBox(height: 12.0);
return new Container(
child: new Column(
children: <Widget>[
spacer,
new RaisedButton(
onPressed: () {Navigator.of(context).pushNamed('/PlanetsPage');},
child: new Text('Get Planet'),
),
spacer,
],
),
);
}
@override
Widget build(BuildContext context){
var spacer = new SizedBox(height: 32.0);
var spacer2 = new SizedBox(height: 15.0);
return new Scaffold(
body: new Center(
child: new Column(
children: <Widget>[
pictureSection(),
mainMenuSection(),
],
),
),
);
}
}
class PlanetsPage extends StatelessWidget{
Widget build(BuildContext context){
return new Scaffold(
body: new Center(
child: new Column(
child: new Text('Hello World'),
),
),
);
}
}
void main(){
runApp(new MaterialApp(
home: new MyHomePage(),
routes: <String, WidgetBuilder> {
'/PlanetsPage': (BuildContext context) => new PlanetsPage(),
},
));
}
按下按钮时,我正试图从主页转到行星页面,按下按钮时只显示错误。我正在使用我的Hauwei Nova进行测试。
答案 0 :(得分:1)
尝试从BuildContext
方法传递build
,而不是使用context
的{{1}}成员。见下文:
MyHomePage