我试图将两个UID连接起来以创建聊天室。正在从Firebase读取一个uid,而从FirebaseAuth.instance读取另一个。
正在分配clientUID,因为我正在将其传递到Text小部件上的另一个页面。但是,聊天室不是在Firestore树中创建的,因此我认为这应该是由于讲师uid造成的。
也许我没有像应该那样调用FirebaseAuth.instance?
代码:
class ClientiPage extends StatefulWidget {
static const String id = 'CLIENTI';
@override
_ClientiPageState createState() => _ClientiPageState();
}
class _ClientiPageState extends State<ClientiPage> {
String chatRoomID;
String clientUID;
Firestore db = Firestore.instance;
String instructor;
void getInstructorId() async {
instructor = (await FirebaseAuth.instance.currentUser()).uid;
}
void saveChatRoom() {
getInstructorId();
DocumentReference chatroomIdRef = db.collection('instructori').document(instructor).collection("chatrooms").document(chatRoomID);
if (chatroomIdRef == null) {
db.collection('instructori').document(instructor).collection("chatrooms").document(chatRoomID);
}
}
void createChatRoom() {
getInstructorId();
chatRoomID = clientUID + instructor;
if(chatRoomID != null) {
saveChatRoom();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ChatPage(
chatRoomID: chatRoomID,
clientUID: clientUID,
),
),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: StreamBuilder(
stream: db.collection('clienti').snapshots(),
builder: (context, snapshot) {
if (snapshot.data == null) {
return Center(
child: CircularProgressIndicator(),
);
} else {
return ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) {
clientUID = snapshot.data.documents[index]["UID"];
return Column(
children: <Widget>[
Divider(
height: 10.0,
),
new ListTile(
onTap: createChatRoom,
title: new Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
new Text(
snapshot.data.documents[index]["numar_telefon"],
style: new TextStyle(
fontWeight: FontWeight.bold,
),
),
],
),
),
],
);
},
);
}
},
),
);
}
}
错误
The getter 'uid' was called on null.
Receiver: null
Tried calling: uid
答案 0 :(得分:3)
instructor
是类ClientiPage
中的一个实例变量,这就是为什么您可以使用属性widget
访问它的原因。但是看来您没有正确初始化它。
uid
将检索当前登录的用户ID,您不必在构造函数中或从其他屏幕传递它,因此您可以执行以下操作:
void saveChatRoom() async {
String userId = (await FirebaseAuth.instance.currentUser()).uid;
DocumentReference chatroomIdRef = db.collection('instructori').document(userId).collection("chatrooms").document(chatRoomID);
if (chatroomIdRef == null) {
db.collection('instructori').document(userId).collection("chatrooms").document(chatRoomID);
}
}
只要用户已登录,就可以使用以下代码uid
来检索(await FirebaseAuth.instance.currentUser()).uid
。无需在屏幕之间传递它。