我正在尝试使用 Firebase 制作简单的登录逻辑,但无法摆脱此错误:
Exception has occurred.
DartError: Bad state: Cannot fire new event. Controller is already firing an event
这是我的代码:
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:identity_retro/models/user_model.dart';
import 'package:uuid/uuid.dart';
class DatabaseOperations {
static final FirebaseDatabase database = FirebaseDatabase.instance;
DatabaseReference ref = FirebaseDatabase.instance.ref();
Future<UserModel?> getUserByEmail(String username) async {
var response = await ref
.child('users')
.orderByChild('username')
.equalTo(username)
.once();
if (!response.snapshot.exists) {
return null;
}
var userMap = Map<String, dynamic>.from(response.snapshot.value as Map);
var user =
UserModel.fromJson(userMap);
return user;
}
Future<UserModel?> getUserById(String id) async {
var response =
await ref.child('users').orderByChild('id').equalTo(id).once();
if (!response.snapshot.exists) {
return null;
}
var user =
UserModel.fromJson(response.snapshot.value as Map<String, dynamic>);
return user;
}
Future<bool> addUser(UserModel user, BuildContext context) async {
if (await getUserByEmail(user.username!) != null)
{
if (context.mounted) {
await showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Error'),
content: const Text('User already exists'),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('OK'),
),
],
);
});
}
return false;
}
var id = Uuid().v4();
await ref.child('users/$id').set({'username': user.username, 'password': user.password});
return await getUserById(id) != null;
}
}
当用户不存在并且尝试在这一行中创建新用户时,在积极的情况下会发生异常:
await ref.child('users/$id').set({'username': user.username, 'password': user.password});
Stacktrace 指向database_reference_web.dart 文件第51 行。这是一个set 方法
但值得一提的是,尽管用户最终还是创建了错误
似乎您尝试在流/控制器仍在处理先前的事件时更新或读取数据
试试这个代码
Future<bool> addUser(UserModel user, BuildContext context) async {
// Check if the user already exists by username
if (await getUserByEmail(user.username!) != null) {
if (context.mounted) {
// Display an error dialog if the user exists
await showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Error'),
content: const Text('User already exists'),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('OK'),
),
],
);
},
);
}
return false;
}
// Generate a unique ID for the user
var id = Uuid().v4();
// Add the user to the Firebase database
await ref.child('users/$id').set({
'id': id, // Ensure that you store the ID in the user object
'username': user.username,
'password': user.password,
});
// Retrieve the user by ID to confirm the insertion
var addedUser = await getUserById(id);
return addedUser != null;
}
如果仍然遇到任何问题,请尝试实现 try catch 并使用断点进行调试