Нулевые значения имени пользователя отображаются в моей консоли Firebase и приложении Flutter.IOS

Программируем под IOS
Ответить
Anonymous
 Нулевые значения имени пользователя отображаются в моей консоли Firebase и приложении Flutter.

Сообщение Anonymous »

Когда я сохраняю в Firebase, такие данные, как имя пользователя, номер телефона и статус, теряются, остается только uid.
Я использую Cubit для управления состоянием.
Код для создания пользователя:
Future createUser(UserEntity user) async {
final userCollection = firestore.collection(FirebaseCollectionConst.users);
final firebase_user = auth.currentUser;
if (firebase_user != null) {
final uid = await getCurrentUID();
final newUser = UserModels(
userName: user.userName,
email: user.email,
phoneNumber: user.phoneNumber,
isOnline: user.isOnline,
uid: uid,
status: user.status,
profileUrl: user.profileUrl,
).toDocument();

try {
userCollection.doc(uid).get().then((userDoc) {
if (!userDoc.exists) {
userCollection.doc(uid).set(newUser);
} else {
userCollection.doc(uid).update(newUser);
}
});
} catch (e) {
throw (" Error occured while creating user");
}
}
}

Код для генерации uid:
Future getCurrentUID() async => auth.currentUser!.uid;

Приведенный ниже код генерирует отображаемое имя, но оно не является постоянным: оно вскоре становится нулевым после того, как становится видимым в Firebse в течение нескольких секунд.
Future updateDisplayName(String userName) async {
User? user = FirebaseAuth.instance.currentUser;

if (user != null) {
// Wait for the update to complete
await user.updateDisplayName(userName);
print("USER - ${user.displayName}");

// Force a reload of the user data from the server
await user.reload();

// Re-fetch the current user to get the refreshed object
user = FirebaseAuth.instance.currentUser;

print("Refreshed user display name: ${user?.displayName}");
return user?.displayName ?? "Unknown User"; // Return the new display name
}

// Return a default value or handle the case where the user is null
return "User not logged in";
}

код Blocprovider в виджете приведен ниже;
if (_nameController.text.isNotEmpty) {
BlocProvider.of(context).submitProfileInfo(
user: UserEntity(
userName: _nameController.text.trim(),
email: "",
phoneNumber: widget.phoneNumber,
status: "your status",
isOnline: false,
profileUrl: profileUrl,
),
);
} else {
toast('Your username is needed to proceed');
}

Код локтя приведен ниже
Future submitProfileInfo({required UserEntity user}) async {
try {
await createUserUsecase.call(user);
emit(CredentialSuccess());
} on SocketException catch (_) {
emit(CredentialFailure());
} catch (_) {
emit(CredentialFailure());
}


Код модели пользователя приведен ниже
class UserModels extends UserEntity {
@override
final String? userName;
@override
final String? email;
@override
final String? phoneNumber;
@override
final bool? isOnline;
@override
final String? uid;
@override
final String? status;
@override
final String? profileUrl;
@override
final String? fcmToken;

const UserModels({
this.userName,
this.email,
this.phoneNumber,
this.isOnline,
this.uid,
this.status,
this.profileUrl,
this.fcmToken,
}) : super(
userName: userName,
email: email,
phoneNumber: phoneNumber,
isOnline: isOnline,
uid: uid,
status: status,
profileUrl: profileUrl,
fcmToken: fcmToken,
);

Map toDocument() => {
'userName': userName,
'email': email,
'phoneNumber': phoneNumber,
'isOnline': isOnline,
'uid': uid,
'status': status,
'profileUrl': profileUrl,
'fcmToken': fcmToken,
};

factory UserModels.fromSnapShot(DocumentSnapshot snapshot) {
final snap = snapshot.data() as Map;

return UserModels(
userName: snap['userName'],
email: snap['email'],
phoneNumber: snap['phoneNumber'],
isOnline: snap['isOnline'],
uid: snap['uid'],
status: snap['status'],
profileUrl: snap['profileUrl'],
fcmToken: snap['fcmToken'],
);
}

String toJson() => json.encode(toDocument());

factory UserModels.fromJson(String source) =>
UserModels.fromSnapShot(json.decode(source));
}


Подробнее здесь: https://stackoverflow.com/questions/797 ... lutter-app
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «IOS»