无法在导航器中使用 Scaffold 全局键的上下文

如何解决无法在导航器中使用 Scaffold 全局键的上下文

我创建了一个简单的应用程序,它通过 firebase 进行了身份验证。在登录屏幕中,如果 usernamepassword 正确,它将显示主屏幕。我使用 Navigator.of(context) 导航到主页。对于 context,我使用了 Scaffold'scontext。在登录页面中,我创建了两个按钮。一个用于登录,另一个用于导航到RegisterPage。对于这两种情况,我都使用 Scaffold's 中的 contextNavigator 进行导航。但是从登录页面导航到注册页面工作正常,但从 LoginPage 导航到 HomePage 不起作用。它说Scaffold key context is null。如果我在导航器的登录按钮中将 Navigator.of(_scaffoldKeylogin.currentContext) 更改为 Navigator.of(context),它将正常工作。为什么它不适用于 Scaffold key

_scaffoldKeylogin 是我的脚手架键

[ERROR:Flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: NoSuchMethodError: The method 'findAncestorStateOfType' was called on null. E/Flutter ( 6114): Receiver: null E/Flutter ( 6114): Tried calling: findAncestorStateOfType<NavigatorState>() E/Flutter ( 6114): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5) E/Flutter ( 6114): #1 Navigator.of (package:Flutter/src/widgets/navigator.dart:2727:40) E/Flutter ( 6114): #2 _LoginState.build.<anonymous closure> (package:e_wallet/Interfaces/login.dart:135:51)

代码

import 'package:e_wallet/Interfaces/home.dart';
import 'package:e_wallet/Interfaces/register.dart';
import 'package:e_wallet/Services/services.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:Flutter/material.dart';

import 'loading.dart';

class Login extends StatefulWidget {
  final Function toggleView;
  Login({this.toggleView});

  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
 final FirebaseAuth _auth = FirebaseAuth.instance;

  final _loginformkey = GlobalKey<FormState>();
 final GlobalKey<ScaffoldState> _scaffoldKeylogin = GlobalKey<ScaffoldState>();
  final _emailcontroller = TextEditingController();
  final _passwordcontroller = TextEditingController();

  bool _obscuretext = true;
  bool _loading=false;
  String _email;
  String _password;
  String _error = "";

  void _togglePass() {
    setState(() {
      _obscuretext = !_obscuretext;
    });
  }

  @override
  Widget build(BuildContext context) {

    return _loading?Loading():Scaffold(
      key: _scaffoldKeylogin,body: Center(
        child: SingleChildScrollView(
          child: Container(
            margin: EdgeInsets.all(10),padding: EdgeInsets.all(10.0),child: Form(
              key: _loginformkey,child: Column(
                children: [
                  Text(
                    "Login",style: TextStyle(fontSize: 20),),TextFormField(
                    controller: _emailcontroller,validator: (value) {
                      if (value.isEmpty) {
                        return "Email cannot be empty";
                      } else {
                        return null;
                      }
                    },onSaved: (value) => _email = value,decoration: Inputdecoration(
                        labelText: "Email",suffixIcon: Icon(Icons.email_outlined)),TextFormField(
                    controller: _passwordcontroller,validator: (value) {
                      if (value.isEmpty) {
                        return "Password cannot be empty";
                      } else {
                        return null;
                      }
                    },onSaved: (value) => _password = value,obscureText: _obscuretext,decoration: Inputdecoration(
                      labelText: "Password",suffixIcon: IconButton(
                        icon: _obscuretext
                            ? Icon(Icons.visibility_off)
                            : Icon(Icons.visibility),onpressed: _togglePass,color: Colors.black54,Container(
                    padding: EdgeInsets.symmetric(horizontal: 40),child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,mainAxisSize: MainAxisSize.min,children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,children: [
                            Text(
                              _error,style: TextStyle(fontSize: 20,color: Colors.red),],Row(
                          children: [
                            Expanded(
                              child: TextButton(
                                  onpressed: () {
                                    _loginformkey.currentState.save();
                                    if (_loginformkey.currentState
                                        .validate()) {}
                                  },child: Text("Forgot Password")),Expanded(
                              child: TextButton(
                                  onpressed: () async {
                                    _loginformkey.currentState.save();
                                    if (_loginformkey.currentState.validate()) {
                                      print("logging in");
                                      try {
                                        setState(() {
                                          _loading=true;
                                        });
                                        print("login auth: : ${_auth}");
                                        UserCredential result = await _auth
                                            .signInWithEmailAndPassword(
                                                email: _email,password: _password);
                                        print(
                                            "loged in sucessfully,user : ${result.user.uid}");

                                        Navigator.of(_scaffoldKeylogin.currentContext).pushReplacement(MaterialPageRoute(builder: (context)=>Home()));

                                      } on FirebaseAuthException catch (e) {
                                        if (e.code == 'user-not-found') {
                                          print("user-not-found");
                                          setState(() {
                                            _error = 'user not found';
                                            _loading=false;
                                          });
                                        } else if (e.code == 'wrong-password') {
                                          print("wrong-password");
                                          setState(() {
                                            _error = 'wrong password';
                                            _loading=false;
                                          });
                                        }else if(e.code == 'network-request-Failed'){
                                          print("error no internet");
                                          print("${e.code}");
                                          setState(() {
                                            _error = 'error: no internet';
                                            _loading=false;
                                          });
                                        }
                                      }
                                    }
                                  },child: Text("LogIn")),Row(
                          children: [
                            Text("Haven't created an account yet?"),Expanded(
                              child: TextButton(
                                  onpressed: () {
                                   // widget.toggleView();
                                    //Navigator.of(context).pushNamed(AppRoutes.);
                                   Navigator.of(_scaffoldKeylogin.currentContext).pushReplacement(MaterialPageRoute(builder: (context)=>Register()));
                                  },child: Text("Register")),);
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?