flutter - 使用不包含 Navigator 的上下文请求的 Navigator 操作的解决方案
问题描述
我正在尝试添加一个图标按钮,该按钮将导航到另一条路线onPressed,并且在我运行应用程序之前没有错误,它向我显示了使用不包含导航器的上下文请求的导航器操作。我错过了什么?谢谢。我删除了脚手架内的代码以便能够发布这个问题
class SignIn extends StatelessWidget {
const SignIn({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(fontFamily: 'Raleway'),
home: Scaffold (
),
body:
Container(
child:
Column(children: [
Text('Sign In', style: TextStyle(
color: Colors.orange,
fontSize: 60.0) ),
SizedBox(height:20,),
TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Email',
),
),
TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Password',
),
),
SizedBox(height: 20,),
ElevatedButton(
child: const Text('Sign In'),
onPressed: null,
),
SizedBox(height: 15,),
Text('Forgot Password ?', style: TextStyle(fontSize: 15),)
],
),
margin: EdgeInsets.only(top: 200),
),
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
DrawerHeader(
decoration: BoxDecoration(
color: Colors.purple,
),
child: Image(image: AssetImage('Images/smsa logo.png'))
),
ListTile(
title: Text('My Account'),
leading: IconButton(onPressed: (){Navigator.push(
context,
MaterialPageRoute(builder: (context) => new MyAccount() ));
}, icon: Icon(Icons.account_circle)
)),
解决方案
问题是,即使MaterialApp
您的小部件内部有 ,您也无法访问它context
,而是无法访问在材料应用程序上方传递的上下文。要解决此问题,您必须MaterialApp
在其自己的小部件中提取
这个你可以粘贴到DartPad上的例子向你展示了如何做到这一点:
import 'package:flutter/material.dart';
const Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(
scaffoldBackgroundColor: darkBlue,
),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: MyWidget(),
),
),
);
}
}
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) { // the context you access here has an MaterialApp above it
return Text(
'Hello, World!',
style: Theme.of(context).textTheme.headline4,
);
}
}
推荐阅读
- asp.net-web-api - 响应正文未从 swagger Swashbuckle 中的自定义错误响应中返回
- reactjs - 单击单个按钮时显示多个 Popconfirm 按钮
- android - 如果被选中的一行的复选框调用 notifyDataSetChanged() 会导致循环
- shell - 替换`里面的字符串
替换任何字符串 ` 用于 solaris 10 UNIX 命令 - excel - Export certain range as pdf based on userform checkbox
- python - 在 matplotlib.figure 子图中添加几个数据集?
- python - 如何使用 python 网络抓取从列表中提取每个输入的 html 文本输出作为列表。我已经编写了代码,但只给出了第一个条目输出
- python - 课堂上的 FastAPI 密钥错误
- html - 如何使用 jquery 修剪和处理当前 url?
- macos - AppleScript Error: Mail got an error: Unrecognized direct parameter type, please specify a string like "John Doe
"