繁体   English   中英

FlutterError(此小部件已卸载,因此 State 不再具有上下文

[英]FlutterError (This widget has been unmounted, so the State no longer has a context

FlutterError(此小部件已卸载,因此 State 不再具有上下文(应被视为已失效)。考虑在“处置”期间取消任何活动工作或使用“已安装”吸气剂来确定 State 是否仍处于活动状态。)

当我注册并从 FirebaseAuth 获取值以保存到 Firebase Cloud Firestore 时,但我无法解决此问题。

My sourcecode:

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';

class RegisterScreen extends StatefulWidget {
  final Function()? onTap;
  const RegisterScreen({super.key, required this.onTap});

  @override
  State<RegisterScreen> createState() => _RegisterScreenState();
}

class _RegisterScreenState extends State<RegisterScreen> {
  //text editing controllers
  final emailController = TextEditingController();

  final passwordController = TextEditingController();

  final confirmPasswordController = TextEditingController();

  //sign user up method
  void signUserUp() async {
    //show loading circle
    showDialog(
        context: context,
        builder: (context) {
          return Center(
            child: CircularProgressIndicator(),
          );
        });

    //try creating the user
    try {
      //check if password is confirmed
      if (passwordController.text == confirmPasswordController.text) {
        await FirebaseAuth.instance
            .createUserWithEmailAndPassword(
              email: emailController.text,
              password: passwordController.text,
            )
            .then((value) => FirebaseFirestore.instance
                    .collection('users')
                    .doc(value.user?.uid)
                    .set({
                  "UID": value.user?.uid,
                  "email": value.user?.email,
                  "joinDate": DateTime.now().toString(),
                }));
      } else {
        //show error message, password don't macthing
        // showErrorMessage("Password don't match!");
        Fluttertoast.showToast(
            msg: "Password don't match!", gravity: ToastGravity.CENTER);
      }
      // pop the loading circle
      // error this here
      //--------------------//
      Navigator.pop(context);
      //-------------------//
    } on FirebaseAuthException catch (e) {
      //pop the loading circle
      //show error message
      Navigator.pop(context);
      showErrorMessage(e.code);
    }
  }

  void showErrorMessage(String message) {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
            backgroundColor: Color.fromARGB(255, 0, 68, 17),
            title: Center(
              child: Text(
                message,
                style: const TextStyle(color: Colors.white),
              ),
            ));
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SingleChildScrollView(
      child: SafeArea(
        child: Center(
          child: Column(
            children: [
              const SizedBox(height: 20),

              //logo
              Image(
                image: AssetImage("assets/images/logo.png"),
                width: 140,
              ),

              // const SizedBox(height: 1),
              //'Let\'s create an account for you'
              Text(
                'Let\'s create an account for you',
                style: TextStyle(
                  color: Color.fromARGB(255, 0, 0, 0),
                  fontSize: 16,
                ),
              ),

              const SizedBox(height: 10),

              //username text field
              MyTextField(
                controller: emailController,
                hintText: "Email",
                obscureText: false,
              ),

              const SizedBox(height: 20),
              //password text field
              MyTextField(
                controller: passwordController,
                hintText: "Password",
                obscureText: true,
              ),
              const SizedBox(height: 20),
              //Confirm password text field
              MyTextField(
                controller: confirmPasswordController,
                hintText: "Confirm Password",
                obscureText: true,
              ),

              const SizedBox(height: 20),

              //sign in button
              Mybutton(
                text: "Sign Up",
                ontap: signUserUp,
              ),
              //or continue with
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 25.0),
                child: Row(
                  children: [
                    Expanded(
                      child: Divider(
                        thickness: 0.5,
                        color: Color.fromARGB(255, 17, 17, 17),
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 25.0),
                      child: Text('Or continue with'),
                    ),
                    Expanded(
                        child: Divider(
                      thickness: 0.5,
                      color: Color.fromARGB(255, 17, 17, 17),
                    ))
                  ],
                ),
              ),

              const SizedBox(height: 10),

              //google + facebook sign in buttons
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  //google button
                  Squaretile(
                      onTap: () {},
                      // onTap: () => AuthService().signInWithGoogle(),
                      imagePath: 'assets/images/google.png'),

                  const SizedBox(width: 5),

                  Squaretile(
                      onTap: () {}, imagePath: 'assets/images/facebook.png'),
                ],
              ),

              const SizedBox(height: 10),

              //not member? register
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    "Already Have a account?",
                  ),
                  const SizedBox(width: 4),
                  GestureDetector(
                    onTap: widget.onTap,
                    child: const Text(
                      'Login now',
                      style: TextStyle(
                          color: Colors.blue, fontWeight: FontWeight.bold),
                    ),
                  ),
                ],
              )
            ],
          ),
        ),
      ),
    ));
  }
}



正如我在您的代码中看到的那样,有两点可能会导致此错误。

  1. 当您调用 FirebaseAuth 时,您同时使用了 await 和 then。 您应该只使用其中一个。
await FirebaseAuth.instance
    .createUserWithEmailAndPassword(
       email: emailController.text,
       password: passwordController.text,
       ).then((value) => 
  1. 当您出现任何Firebase错误时,您正在弹出页面,然后尝试显示消息警报。
} on FirebaseAuthException catch (e) {
      //pop the loading circle
      //show error message
      Navigator.pop(context);
      showErrorMessage(e.code);
    }

在这里,您的消息提醒在注册页面上,您在显示提醒之前弹出页面。 这导致代码尝试在没有注册页面的情况下在注册页面上显示警报。 你应该只显示错误而不返回。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM