如何获取当前的 Firebase UID 并将其写入实时数据库?
Posted
技术标签:
【中文标题】如何获取当前的 Firebase UID 并将其写入实时数据库?【英文标题】:How do I get the current Firebase UID and write it to Realtime Database? 【发布时间】:2022-01-17 06:12:38 【问题描述】:我按照教程创建了这个 AuthService 类。这很好用。
import 'package:firebase_auth/firebase_auth.dart';
import 'package:app/models/user.dart' as UserModel;
class AuthService
final FirebaseAuth _auth = FirebaseAuth.instance;
// create CurrentUser object based on Firebase user object
UserModel.User? _userFromFirebaseUser(User? user)
// return user != null ? UserModel.User(uid: user.uid) : null;
if (user != null)
return UserModel.User(uid: user.uid);
else
return null;
//auth change user stream
Stream<UserModel.User?> get user
return _auth.authStateChanges()
// .map((User? user) => _userFromFirebaseUser(user));
.map(_userFromFirebaseUser);
//Sign in anonymously
Future signInAnon() async
try
UserCredential result = await _auth.signInAnonymously();
User? user = result.user;
return _userFromFirebaseUser(user);
catch(e)
print(e.toString());
return null;
//Sign in with email and pass
Future signInWithEmailAndPassword(String email, String password) async
try
UserCredential result = await _auth.signInWithEmailAndPassword(email: email, password: password);
User? user = result.user;
return _userFromFirebaseUser(user);
catch(e)
print(e.toString());
return null;
//register with email and password
Future registerWithEmailAndPassword(String email, String password) async
try
UserCredential result = await _auth.createUserWithEmailAndPassword(email: email, password: password);
User? user = result.user;
return _userFromFirebaseUser(user);
catch(e)
print(e.toString());
return null;
//sign out
Future signOut() async
try
return await _auth.signOut();
catch(e)
print(e.toString());
return null;
但是,我现在想在用户在聊天屏幕上发送聊天时使用当前的 Firebase UID 将其写入实时数据库。我该怎么做?我在下面尝试过,但迷路了(请参阅 FloatingActionButton 的 OnPressed 事件)。
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:app/services/auth.dart';
import 'package:app/models/user.dart';
class Chat extends StatelessWidget
Chat(Key? key) : super(key: key);
final database = FirebaseDatabase.instance.reference();
@override
Widget build(BuildContext context)
final groupChatRef = database.child('GroupID');
return Scaffold(
appBar: AppBar(
title: Text('Group Chat Screen'),
// actions: [
// TextButton.icon(
// onPressed:
// Navigator.pop(context);
// ,
// icon: icon,
// label: label
// )
// ],
),
body: Align(
alignment: Alignment.bottomLeft,
child: Row(
children: [
Expanded(
child: TextField(
decoration: InputDecoration(
hintText: "Write message...",
)
),
),
FloatingActionButton(
onPressed: ()
var uid;
final user = User(uid: uid);
final myAuth = AuthService();
print('MyAuth.user:');
//This is where I get lost...
,
child: Icon(Icons.send,color: Colors.white,size: 18,),
backgroundColor: Colors.blue,
elevation: 0,
)
],
),
)
);
【问题讨论】:
【参考方案1】:您可以通过在auth服务中添加getter来获取用户uid
class AuthService
...
User? get currentUser => _auth.currentUser;
...
然后在您的浮动操作按钮中获取该用户并使用它的 uid
此外,使用依赖注入并在每次需要时停止创建实例会更好。
onPressed: ()
final String uid = authService.currentUser!.uid;
// do other things
,
【讨论】:
谢谢!依赖注入的东西是什么意思?我在我的代码中哪里创建了太多实例? @whatwhatwhat 您在 onPressed 函数中创建了一个 'AuthService' 的实例,您可以一次创建一个AuthService
的实例,并在您需要的每个地方使用它。您可以使用Provider 之类的包将依赖项注入BuildContext
或使用GetIt 之类的包将它们注入内存本身。然后你可以得到这样的实例 context.read<AuthService>()
或使用 GetIt GetIt.I.get<AuthService>()
并使用它。以上是关于如何获取当前的 Firebase UID 并将其写入实时数据库?的主要内容,如果未能解决你的问题,请参考以下文章
如何从所有用户 ID (UID) 中获取特定值并保存在 RecyclerView Firebase UI