我正在嘗試創建一個用戶提要,就像使用 Firebase 和 GetX 的 twitter 一樣。
在代碼片段中是我的功能..
List<PostModel> postListFromSnapshot(QuerySnapshot snapshot) {
return snapshot.docs.map((doc) {
return PostModel(
id: doc.id,
text: (doc.data() as dynamic)["text"] ?? "",
creator: (doc.data() as dynamic)["creator"] ?? "",
timestamp: (doc.data() as dynamic)["timestamp"] ?? 0,
);
}).toList();
}
Future<List<PostModel>> getFeed() async {
List<String> usersFollowing = await UserService() //['uid1', 'uid2']
.getUserFollowing(FirebaseAuth.instance.currentUser!.uid);
QuerySnapshot querySnapshot = await FirebaseFirestore.instance.collection("posts").where('creator', whereIn: usersFollowing)
.orderBy('timestamp', descending: true)
.get();
return postListFromSnapshot(querySnapshot);
}
我要做的是顯示 Future 函式 getFeed(),我使用 GetX 進行狀態管理。所以,我的問題是如何使用 ListView.Builder() 顯示此函式的結果
這是我使用 Future builder 的方式
FutureBuilder(
future: _.listPost,
initialData: [PostModel(id: "2", creator: "Fm", text: "Testing", timestamp: Timestamp.now())],
builder: (BuildContext context, AsyncSnapshot snapshot){
if(snapshot.hasData == null){
return Text("Data is available");
} else{
return ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data.toString().length,
itemBuilder: (context, index){
PostModel posts = snapshot.data[index];
return Column(
children: [
Text(posts.text)
],
);
},
);
}
},
)
這是我得到的錯誤
The following NoSuchMethodError was thrown building:
The method '[]' was called on null.
Receiver: null
Tried calling: [](3)
它還指出了
PostModel 帖子行上的錯誤。準確地說,[index]
uj5u.com熱心網友回復:
首先,制作AsyncSnapshot snapshot
一個AsyncSnapshot<List<PostModel>> snapshot
. 這不是你的主要問題,但它會讓事情變得更容易正確輸入,而不必猜測使用dynamic
.
你的問題是那hasData
是一個bool
. 它是true
or false
,但從不是null
。我想知道你是如何通過編譯器的。您是否使用過時的 Flutter 版本?你應該檢查一下,你的編譯器是你的朋友,如果它不能正確地幫助你,這將是一條艱難而崎嶇的道路。
無論如何,你應該檢查是否有資料,如果沒有,你還在等待:
FutureBuilder(
future: _.listPost,
builder: (BuildContext context, AsyncSnapshot<List<PostModel>> snapshot){
if(!snapshot.hasData){
return CircularProgressIndicator();
} else {
final postList = snapShot.requireData;
return ListView.builder(
shrinkWrap: true,
itemCount: postList .length,
itemBuilder: (context, index){
final post = postList[index];
return Column(
children: [
Text(post.text)
],
);
},
);
}
},
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/484331.html