import 'package:flutter/material.dart';
main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(primarySwatch: Colors.blue),
home: Scaffold(
appBar: AppBar(
title: Text("Page 1"),
),
body: Center(
child: Column(
children: <Widget>[
MaterialButton(
child: Text("Next Page"),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => nextPage()),
);
},
color: Colors.red,
)
],
),
),
),
);
}
}
class nextPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(primarySwatch: Colors.green),
home: Scaffold(
appBar: AppBar(
title: Text("Page 2"),
),
body: Center(
child: Column(
children: <Widget>[
MaterialButton(
child: Text("Go Back!"),
onPressed: () {
Navigator.pop(context);
},
color: Colors.red,
)
],
),
),
),
);
}
}
这是我用来导航到新页面的代码,但是即使编译器未引发任何错误,我也遇到了问题
这是我收到的错误消息
引发了另一个异常:在不包含导航器的上下文中请求了导航器操作。
单击按钮时出现此错误
最佳答案
您需要home : Builder( builder: (context) =>
和Second Page删除MaterialApp
MaterialApp(
home: Builder(
builder: (context) => Scaffold(
appBar: AppBar(
title: Text("Page 1"),
),
body: Center(
child: Column(
children: <Widget>[
MaterialButton(
child: Text("Next Page"),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => nextPage()),
);
},
color: Colors.red,
)
],
),
),
),
),
完整的代码
import 'package:flutter/material.dart';
main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Builder(
builder: (context) => Scaffold(
appBar: AppBar(
title: Text("Page 1"),
),
body: Center(
child: Column(
children: <Widget>[
MaterialButton(
child: Text("Next Page"),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => nextPage()),
);
},
color: Colors.red,
)
],
),
),
),
),
);
}
}
class nextPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Page 2"),
),
body: Center(
child: Column(
children: <Widget>[
MaterialButton(
child: Text("Go Back!"),
onPressed: () {
Navigator.pop(context);
},
color: Colors.red,
)
],
),
),
);
}
}
关于flutter - 我正在尝试通过点击按钮来打开另一个事件,但它显示了一些错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58537774/