使用 FirebaseAuth 时捕获异常

问题描述 投票:0回答:1

我正在尝试使用 firebase 身份验证创建登录名,我已经设法创建新用户并将其存储在系统中,如果我正确输入用户名和密码,我可以登录,但是当我错误地输入 2 个数据之一时,我无法捕获异常,我的应用程序崩溃了enter image description here

我将代码留在执行 try catch 的位置

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

class LoginScreen extends StatelessWidget {
  final TextEditingController emailController = TextEditingController();
  final TextEditingController passwordController = TextEditingController();

  Future<void> signInWithEmailAndPassword(BuildContext context) async {
  try {
    // Intenta iniciar sesión con las credenciales proporcionadas
    await FirebaseAuth.instance.signInWithEmailAndPassword(
      email: emailController.text,
      password: passwordController.text,
    );
    // Inicio de sesión exitoso, realizar acciones necesarias
  } on FirebaseAuthException catch (e) {
    // Captura la excepción específica FirebaseAuthException
    print('Failed with error code: ${e.code}');
    print(e.message);
    // Mostrar un mensaje de error al usuario
  } 
}


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Inicio de Sesión')),
      body: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            TextFormField(
              controller: emailController,
              decoration: const InputDecoration(labelText: 'Correo Electrónico'),
              validator: (value) {
                if (value == null || value.isEmpty || !value.contains('@')) {
                  return 'Por favor, ingresa un correo electrónico válido';
                }
                return null;
              },
            ),
            const SizedBox(height: 20.0),
            TextFormField(
              controller: passwordController,
              decoration: const InputDecoration(labelText: 'Contraseña'),
              obscureText: true,
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return 'Por favor, ingresa tu contraseña';
                }
                return null;
              },
            ),
            const SizedBox(height: 20.0),
            ElevatedButton(
              onPressed: () {
                if (emailController.text.trim().isEmpty || 
                    passwordController.text.trim().isEmpty) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('Por favor, completa todos los campos')),
                  );
                } else {
                  signInWithEmailAndPassword(context);
                }
              },
              child: const Text('Iniciar Sesión'),
            ),
          ],
        ),
      ),
    );
  }
}

我希望我能发现错误并能够给出个性化的消息

flutter firebase dart authentication firebase-authentication
1个回答
0
投票

试试这个:

Future<void> signInWithEmailAndPassword(BuildContext context) async {
String authException='';
try {
    // Intenta iniciar sesión con las credenciales proporcionadas
    await FirebaseAuth.instance.signInWithEmailAndPassword(
      email: emailController.text,
      password: passwordController.text,
    );
    // Inicio de sesión exitoso, realizar acciones necesarias
  } on FirebaseAuthException catch (e) {
    if (e.code == 'user-not-found') {
    print('No user found for that email.');
    authException='No user found for that email';
  } else if (e.code == 'wrong-password') {
    print('Wrong password provided for that user.');
    authException='Wrong password provided for that user';
  }
  } 
}
© www.soinside.com 2019 - 2024. All rights reserved.