我正在撰寫一個社交媒體應用程式,用戶可以在其中發布和閱讀其他用戶的帖子。我的問題在這里,我想從寫帖子的用戶那里得到一個更新的名字,這樣當用戶更新它的名字時,最新的名字應該出現在帖子上。
在我的這段代碼中,我收到了錯誤
引數型別“Future<String?>”不能分配給引數型別“String”
Widget postList (){
return Container(
child: StreamBuilder(
stream: some Stream
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot){
return !snapshot.hasData ?
CircularProgressIndicator():
ListView(
children: snapshot.data!.docs.map((document) {
return InkResponse(
child: Container(
child: Column(
children: <Widget>[
Row(
children: [
// I'm having trouble here
/** What I want to happen is to retrieve the NAME of the user using UID so that even if the
Writer changes his name, the latest name shall appear on this */
Text ( getWriterInformation(uid: document['poster_uid']),
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16)),
],
),
],
),
),
);
}).toList(),
);
},
);
}
Future <String?> getWriterInformation ({required String uid}) async {
await Users.doc(uid).get().then((value){
return value['display_name'].cast<String>();
});
}
}
如果您能推薦除我的方式之外的任何其他方式,我將很高興地感激它。
uj5u.com熱心網友回復:
用于小FutureBuilder()部件Text():
FutureBuilder(
future: getWriterInformation(uid: document['poster_uid']),
builder: (BuildContext context, AsyncSnapshot<String> text) {
return Text(text.data);
})
這個:
return Container(
child: StreamBuilder(
stream: some Stream
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot){
return !snapshot.hasData ?
CircularProgressIndicator():
ListView(
children: snapshot.data!.docs.map((document) {
return InkResponse(
child: Container(
child: Column(
children: <Widget>[
Row(
children: [
// I'm having trouble here
/** What I want to happen is to retrieve the NAME of the user using UID so that even if the
Writer changes his name, the latest name shall appear on this */
FutureBuilder(
future: getWriterInformation(uid: document['poster_uid']),
builder: (BuildContext context, AsyncSnapshot<String> text) {
return Text(text.data);
})
],
),
],
),
),
);
}).toList(),
);
},
);
uj5u.com熱心網友回復:
這是因為 getWriterInformation 回傳未來字串的型別。您不能將未來的字串 val 分配給 String。文本小部件只接受字串。為此,您需要 futureBuilder。來自 firebase 的一些資料需要時間,因此在頁面啟動時會顯示加載器,直到資料到來。
Saitoh Akira 的回答是正確的。
uj5u.com熱心網友回復:
如果您正在使用它,您可以.snapshots()使用它從 firebase 獲取實時更新
Widget postList (){
return Container(
child: StreamBuilder(
stream: some Stream
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot){
if(!snapshot.hasData ?){
return CircularProgressIndicator();}
else {
return ListView.builder(
count: snapshot.docs.length,
builder: (context, snapshot) {
Map<String, dynamic> data = snapshot.docs!.data as Map<String, dynamic>;
return InkResponse(
child: Container(
child: Column(
children: <Widget>[
Row(
children: [
Text(data['name'])
],
),
],
),
),
);
}
)}
/// this is not required ?
Future <String?> getWriterInformation ({required String uid}) async {
await Users.doc(uid).get().then((value){
return value['display_name'].cast<String>();
});
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/489971.html
