Flutter:创建帐户而不注销导致错误



我试图遵循这里的解决方案,Flutter: Firebase认证创建用户而不登录,

Future<void> register(BuildContext context) async {
FirebaseApp app = await Firebase.initializeApp(
name: 'secondary', options: Firebase.app().options);
try {
UserCredential userCredential = await FirebaseAuth.instanceFor(app: app)
.createUserWithEmailAndPassword(
email: email.text, password: password.text);
Navigator.push(
context,
MaterialPageRoute(builder: (context) => createSetupPage()),
);
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
setState(() {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('Weak Password'),
));
});
} else if (e.code == 'email-already-in-use') {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('Email Already In Use'),
));
}
} catch (e) {
print(e);
}
}

当我创建一个帐户时,它工作一次,然后给我这个错误,当我尝试使用此代码创建另一个具有相同名称的帐户时,它在控制台

中给我这个错误
E/flutter ( 1191): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: [core/duplicate-app] A Firebase App named "secondary" already exists

我如何解决这个问题,使我可以保持多个帐户,而不从一个帐户注销?似乎我需要在Firebase中每个人都有一个新名字。初始化应用程序部分

您的Firebase应用程序实例应该只在每次应用程序启动时初始化一次。

你应该移动初始化块:

FirebaseApp app = await Firebase.initializeApp(
name: 'secondary', options: Firebase.app().options);

在方法调用之外并在启动时初始化:

void main() async {
FirebaseApp app = await Firebase.initializeApp(
name: 'secondary', options: Firebase.app().options);
//...
}

则可以在需要时将FirebaseApp实例作为参数传递给调用者:

Future<void> register(FirebaseApp app, BuildContext context) async {
try {
UserCredential userCredential = await FirebaseAuth.instanceFor(app: app)
.createUserWithEmailAndPassword(
email: email.text, password: password.text);
Navigator.push(
context,
MaterialPageRoute(builder: (context) => createSetupPage()),
);
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
setState(() {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('Weak Password'),
));
});
} else if (e.code == 'email-already-in-use') {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('Email Already In Use'),
));
}
} catch (e) {
print(e);
}
}

也就是说,你可以完全省略传递FirabseApp实例,因为firebase_auth库将在引导时保持默认应用程序实例。

在应用程序启动步骤中调用await Firebase.initializeApp();之后,您可以简单地访问引用默认应用程序的FirebaseAuth.instance:

Future<void> register(BuildContext context) async {
try {
UserCredential userCredential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: email.text, password: password.text);
Navigator.push(
context,
MaterialPageRoute(builder: (context) => createSetupPage()),
);
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
setState(() {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('Weak Password'),
));
});
} else if (e.code == 'email-already-in-use') {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('Email Already In Use'),
));
}
} catch (e) {
print(e);
}
}

相关内容

  • 没有找到相关文章

最新更新