I have a chat app in Flutter using Firestore, and I have two main collections:
chats
, which is keyed on auto-ids, and hasmessage
,timestamp
, anduid
fields.users
, which is keyed onuid
, and has aname
field
In my app I show a list of messages (from the messages
collection), with this widget:
class ChatList extends StatelessWidget {
@override
Widget build(BuildContext context) {
var messagesSnapshot = Firestore.instance.collection("chat").orderBy("timestamp", descending: true).snapshots();
var streamBuilder = StreamBuilder<QuerySnapshot>(
stream: messagesSnapshot,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> querySnapshot) {
if (querySnapshot.hasError)
return new Text('Error: ${querySnapshot.error}');
switch (querySnapshot.connectionState) {
case ConnectionState.waiting: return new Text("Loading...");
default:
return new ListView(
children: querySnapshot.data.documents.map((DocumentSnapshot doc) {
return new ListTile(
title: new Text(doc['message']),
subtitle: new Text(DateTime.fromMillisecondsSinceEpoch(doc['timestamp']).toString()),
);
}).toList()
);
}
}
);
return streamBuilder;
}
}
But now I want to show the user's name (from the users
collection) for each message.
I normally call that a client-side join, although I'm not sure if Flutter has a specific name for it.
I've found one way to do this (which I've posted below), but wonder if there is another/better/more idiomatic way to do this type of operation in Flutter.
So: what is the idiomatic way in Flutter to look up the user name for each message in the above structure?