Flutter Firebase [firebase_auth/network-request-failed]发生网络错误(例如超时、连接中断或主机不可访问

xtupzzrd  于 2023-01-21  发布在  Flutter
关注(0)|答案(4)|浏览(298)

我正在使用firebase auth实现Google登录,并将相应的用户信息存储在Cloud Firestore和共享首选项中。在手机上运行应用程序并点击登录/注册按钮时,弹出窗口显示可用帐户。但当我选择所需的Google帐户时,弹出窗口消失,并出现如下错误:

[firebase_auth/network-request-failed]发生网络错误(如超时、连接中断或无法访问主机)。

此外,Cloud Firestore控制台和Firebase Auth的Users部分都没有存储帐户和用户详细信息,但这些详细信息存储在共享首选项中,当我重新运行应用程序时,可以直接导航到主页。

class Login extends StatefulWidget {
  static final String id = 'login_screen';
  const Login({Key? key}) : super(key: key);

  @override
  State<Login> createState() => _LoginState();
}

class _LoginState extends State<Login> {
  final GoogleSignIn googleSignIn = new GoogleSignIn();
  final FirebaseAuth firebaseAuth = FirebaseAuth.instance;
  late SharedPreferences preferences;
  bool loading = false;
  bool isLoggedIn = false;
  User? user;
  @override
  void initState() {
    super.initState();
    isSignedIn();
  }

  void isSignedIn() async {
    setState(() {
      // loading = true;
    });
    preferences = await SharedPreferences.getInstance();
    isLoggedIn = await googleSignIn.isSignedIn(); //Check if user is signed in

    if (isLoggedIn) {
      Navigator.pushReplacement(
          context,
          MaterialPageRoute(
              builder: (context) =>
                  HomePage())); //Helps us to keep user logged in once he has logged in so that user doesn't come to log in screen again on pressing back.
      setState(() {
        loading = false;
      });
    }
  }

  Future signInWithGoogle() async {
    preferences = await SharedPreferences.getInstance();
    setState(() {
      loading = true;
    });
    GoogleSignInAccount? googleUser = await googleSignIn.signIn();

    if (googleUser != null) {
     final GoogleSignInAuthentication googleSignInAuthentication =
          await googleUser.authentication;

      final AuthCredential credential = GoogleAuthProvider.credential(
        accessToken: googleSignInAuthentication.accessToken,
        idToken: googleSignInAuthentication.idToken,
      );
      final UserCredential userCredential =
          await firebaseAuth.signInWithCredential(credential);
      user = userCredential.user;
      if (user != null) {
        final QuerySnapshot result = await FirebaseFirestore.instance
            .collection("users")
            .where("id", isEqualTo: user?.uid)
            .get();
        //Check whether the id of that field is equal to the id of the user we obtained above.
        //If we have it, it means the user is already signed up to the application.
        final List<DocumentSnapshot> docs = result.docs;
        if (docs.length ==
            0) //If the docs are empty means that user does not exist in our database, therfore sign hom up
        {
          //Add user to our collection
          FirebaseFirestore.instance.collection("users").doc(user?.uid).set({
            "id": user?.uid,
            "username": user?.displayName,
            "profilePicture": user?.photoURL,
            "phNo": user?.phoneNumber,
            "email": user?.email,
          });
          await preferences.setString('id', user!.uid);
          await preferences.setString('userName', user!.displayName ?? ' ');
          await preferences.setString('photoUrl', user!.photoURL ?? ' ');
          await preferences.setString('email', user!.email ?? '');
        } else {
          await preferences.setString('id', docs[0]['id']);
          await preferences.setString('userName', docs[0]['username']);
          await preferences.setString('photoUrl', docs[0]['photoUrl']);
          await preferences.setString('email', docs[0]['email']);
        }
        Navigator.popAndPushNamed(context, HomePage.id);
        setState(() {
          loading = false;
        });

      } else {}

      
    }
  }
uhry853o

uhry853o1#

这可能是由于您的Internet连接

确保️您的手机或模拟器可以访问互联网
还要️确保您已在AndroidManifest.xml文件中为应用添加了ACCESS_INTERNET权限

xeufq47z

xeufq47z2#

您是否在firebase项目设置中添加了SHA证书指纹?不添加SHA可能会导致此问题。

uz75evzq

uz75evzq3#

与这个错误斗争了几个小时,得到了人们指出的每一个解决方案。
其中一个终于解决了我的问题。我不知道哪个能解决你的问题,所以试试所有的方法吧。
1.停用您的仿真器(关闭包含本地主机的终端),
1.从表单标签中获取按钮,首选div标签
1.从提交类型中获取按钮,
1.为你的按钮添加这段代码不要冒泡:
1.如果确实要在localhost上进行测试,请使用127.0.0.1/而不是localhost/

document.getElementById('signup-btn').addEventListener('click', function(event){
    event.preventDefault()

1.如果你使用的是“HTTPS Everywhere”扩展,那么去“HTTPS Everywhere”设置,然后点击“禁用HTTPS Everywhere为这个网站”按钮。
1.禁用CORS Chrome插件
1.确保传递的是实际值而不是对按钮的引用
1.我更喜欢在 chrome 而不是边缘上测试。

7kqas0il

7kqas0il4#

我得到了一个表单标签的按钮,首选的div标签得到了答案谢谢

相关问题