Когда я сохраняю в 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
Нулевые значения имени пользователя отображаются в моей консоли Firebase и приложении Flutter. ⇐ IOS
Программируем под IOS
1760495841
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));
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79790759/null-values-of-username-are-showing-in-my-firebase-console-and-flutter-app[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия