如何倾听来自firebase的流中的变化



我正在从这个流生成器中获取数据,并将其显示在一个有状态的小部件中。

Widget chatRoomsLists() {
return StreamBuilder<QuerySnapshot>(
stream:  FirebaseFirestore.instance
.collection('chatrooms').orderBy("lastMessageSendTs", descending: true)
.where("users", arrayContains:myUserName)
.snapshots(),
builder: (context, snapshot){
return snapshot.hasData ? ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data!.docs.length,
itemBuilder: (context,index){
DocumentSnapshot ds = snapshot.data!.docs[index];

return  ChatRoomListTile(ds['lastMessage'], ds.id,myUserName! );

}) : Center(child: CircularProgressIndicator());
}) ;
}

并在这里显示

class ChatRoomListTile extends StatefulWidget {
final String lastMessage , chatRoomId, myUsername;
ChatRoomListTile(this.lastMessage, this.chatRoomId, this.myUsername,);
@override
_ChatRoomListTileState createState() => _ChatRoomListTileState();
}
class _ChatRoomListTileState extends State<ChatRoomListTile> {
String profilePicUrl = 'https://miro.medium.com/max/875/0*H3jZONKqRuAAeHnG.jpg' , name = ''  ,username = "";

getThisUserInfo() async {
print('userinfo called');
username = widget.chatRoomId.replaceAll(widget.myUsername, "").replaceAll("_", "");
QuerySnapshot querySnapshot = await DatabaseMethods().getUserInfo(username);
// print("something bla bla ${querySnapshot.docs[0].id} ${querySnapshot.docs[0]["name"]}  ${querySnapshot.docs[0]["profileURL"]}");
name = "${querySnapshot.docs[0]["name"]}";
profilePicUrl = "${querySnapshot.docs[0]["profileURL"]}";
setState(() {});
}
@override
void initState() {
getThisUserInfo();
super.initState();
}

@override
Widget build(BuildContext context) {
print('BUILDING IS CALLED');

return GestureDetector(
onTap: () {
print('name is $username and ${widget.myUsername}');
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Chatting(username, widget.myUsername)));
},
child: Column(
children: [
Container(
margin: EdgeInsets.symmetric(vertical: 8),
child: Row(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(30),
child: Image.network(profilePicUrl,
height: 40,
width: 40,
),
),
SizedBox(width: 12),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
name,
style: TextStyle(fontSize: 16),
),
SizedBox(height: 3),
SizedBox(width: 220,
child: Text(widget.lastMessage,overflow: TextOverflow.ellipsis)),
],
)
],
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: Divider(thickness: 0.5 ,),
)
],
),
);
}
}

每次widget.lastmessage发生变化时,我都想打电话给get这个未来的getThisUserInfo。我该怎么做?当我在构建中调用这个future时,它会被一次又一次地不停地调用。那么,只有当有新消息时,我怎么才能调用它呢?

我建议您查看构建器的构造并检查snapshot().listen()方法,您可以参考这个类似的问题。

对于您的后续问题,很难说是什么导致了这种重复的更新,因为它可能是很多事情,而您的代码中没有任何内容表明这一点,所以话虽如此,我会想到一些逻辑,允许您检查您想要进行的更新是否已经发生,也许需要花费读取时间,这比写入时间便宜。

相关内容

  • 没有找到相关文章

最新更新