我正在尝试创建一个示例,并且我正在尝试从 a 创建一个导航statefulWidget
,我收到以下错误,大多数示例都讨论了无状态小部件之间的导航
flutter: ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
flutter: The following assertion was thrown while handling a gesture:
flutter: Navigator operation requested with a context that does not include a Navigator.
flutter: The context used to push or pop routes from the Navigator must be that of a widget that is a
flutter: descendant of a Navigator widget.
下面是我的代码
import 'package:flutter/material.dart';
import 'package:flutter_app/second.dart';
main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _MyAppState();
}
}
class _MyAppState extends State<MyApp> {
var strings = ["Flutter", "Java", "SWift"];
var displayText = "";
void onPressed() {
var list = List<int>.generate(3, (int index) => index); // [0, 1, 4]
list.shuffle();
print(list);
setState(() {
displayText = strings[list.first];
});
}
@override
Widget build(BuildContext context) {
var scaffold = Scaffold(
appBar: AppBar(
title: Text('Flutter Second'),
),
body: Container(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
displayText,
style: TextStyle(
color: Colors.red,
fontStyle: FontStyle.normal,
fontWeight: FontWeight.bold,
fontSize: 30.0),
),
Padding(
padding: EdgeInsets.all(10.0),
),
RaisedButton(
child: Text('Change'),
textColor: Colors.black,
onPressed: () {
Navigator.pushNamed(context, '/second'); // Fails here
},
)
],
),
)),
);
return MaterialApp(
home: scaffold,
routes: {
'/second': (context) => SecondScreen(),
},
);
}
}
以下是我尝试过的
使用 Navigator.of(context)
包装
statefulwidget
为从无状态小部件创建的材料应用程序的主页。
但没有运气。