尝试使用导航器时出现异常



我得到一个异常:FlutterError(使用不包括Navigator的上下文请求的Navigator操作。用于从Navigator推送或弹出路由的上下文必须是Navigator小部件的子代小部件的上下文。(

这是第一页的重要代码(跳过了一些与…无关的代码(:

import 'package:google_fonts/google_fonts.dart';
import 'register.dart';
void main() async {
...
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
...
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
textTheme: GoogleFonts.interTextTheme(
Theme.of(context).textTheme,
)),
home: Scaffold(
body: Container(
width: double.infinity,
...
Align(
alignment: Alignment.centerRight,
child: TextButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SecondRoute()));
},
child: Text(
"Forgot Password?",
style: GoogleFonts.inter(
fontWeight: FontWeight.w600,
),
),
),
),
...
),
));

}}

这是第二页:

import 'package:flutter/material.dart';
class SecondRoute extends Navigator {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text("Second Route"),
),
);
}
}

没有语法错误,只有在运行代码时抛出的异常。我已经尝试过寻找解决方案,但据我所知,将材料应用程序放入runApp((方法的另一种方法不适用于我使用文本主题和上下文的方式。

如果我需要提供更多的代码或上下文,请告诉我。

如有任何帮助,我们将不胜感激!

尝试更改:

class SecondRoute extends Navigator {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text("Second Route"),
),
);
}
}

至:

class SecondRoute extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text("Second Route"),
),
);
}
}

Edit,还可以将scaffold从_MyAppState移动到它自己的小部件中。

class FirstRoute extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: SizedBox(
width: double.infinity,
child: Align(
alignment: Alignment.centerRight,
child: TextButton(
onPressed: () {
print('hello');
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondRoute()),
);
},
child: Text(
"Forgot Password?",
style: GoogleFonts.inter(
fontWeight: FontWeight.w600,
),
),
),
),
),
);
}
}

然后像这样在_MyAppState中使用:

class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
textTheme: GoogleFonts.interTextTheme(
Theme.of(context).textTheme,
)),
home: FirstRoute(),
);
}
}

相关内容

最新更新