当我试图在appBar中显示带有其名称的用户状态时,我遇到了这个问题:
appBar: AppBar(
title: StreamBuilder<DocumentSnapshot>(
stream: _firestore.collection('users').doc(userMap['uid']).snapshots(),
builder: (context, snapshot){
if (snapshot.data != null){
return Container(
child: Column(
children: [
Text(userMap['name']),
Text(
snapshot.data!['status'],
style: TextStyle(fontSize: 14),
)
],
),
);
}else{
return Container();
}
}
),
backgroundColor: Colors.white,
leading: IconButton(
icon:Icon(Icons.arrow_back_rounded, color: Colors.black,), onPressed: () {
Navigator.of(context)
. pushReplacement(MaterialPageRoute(builder: (_) => chatpage()));},
),
),
查看用户状态的所有过程在firebase中工作,我认为问题在第一部分,但我展示了其余的代码。
class _chatpageState extends State<chatpage> with WidgetsBindingObserver{
Map<String,dynamic>? userMap;
bool isLoading = false;
final FirebaseAuth _auth = FirebaseAuth.instance;
final TextEditingController _search = TextEditingController();
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
@override
void initState(){
super.initState();
WidgetsBinding.instance!.addObserver(this);
setStatus("Online");
}
void setStatus(String status)async{
await _firestore.collection('users').doc(_auth.currentUser!.uid).update({
"status": status
});
}
@override
void didChangeAppLifecycleState(AppLifecycleState state){
if(state == AppLifecycleState.resumed){
setStatus("Online");
//online
}else{
setStatus("Offline");
//offline
}
}
还有一小部分我的方法:
await _firestore.collection('users').doc(_auth.currentUser!.uid).set({
"name": name,
"email": email,
"status": "Unavalible",
"uid": _auth.currentUser!.uid,
});
如果有人能帮助我,我会非常感激的:)
将appBar中的snapshot.data!['status']
更改为snapshot.data.get('status')
(如果您确定'status'字段存在)
或
dynamic data = snapshot.data.data();
print(data['status']);
return Container(
child: Column(
children: [
Text(userMap['name']),
Text(
data['status'],
style: TextStyle(fontSize: 14),
)
],
),
);
try this
if (snapshot.data != null){
final snapshotData = snapshot.data!.data(); //retrive data from snapshot
return Container(
child: Column(
children: [
Text(userMap['name']),
Text(
snapshotData["status"]??"", //?? checks if value is null. so you can add emty string or show its updating or undefined
style: TextStyle(fontSize: 14),
)
],
),
);
}else{
return Container();
}
}