【发布时间】:2021-09-27 20:20:40
【问题描述】:
我正在从这个流构建器获取数据并将其显示在有状态的小部件中。
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 this future getThisUserInfo。我怎样才能做到这一点 ?
当我在构建中调用这个未来时,它会一次又一次地不停地被调用。那么我怎么能只在只有新消息时才调用它呢?
【问题讨论】:
-
我建议您检查构建器的构造并检查
snapshot().listen()方法。可以参考这个similar issue -
我按照建议使用了,但如果函数被调用两次,它仍然会更新。
final up = FirebaseFirestore.instance; StreamSubscription getUpdate() { return up.collection('chatrooms') .snapshots().listen((event) { event.docChanges.forEach((change) { return getThisUserInfo(); }); }); }
标签: firebase flutter dart google-cloud-firestore firebase-cloud-messaging