在Flutter中,我有一个使用Firestore的聊天应用程序,并且有两个主要集合:
chats
(在自动ID上键入),并具有message
,timestamp
和uid
字段。users
,在uid
上键入并具有一个name
字段在我的应用中,我使用以下小部件显示消息列表(来自messages
集合)
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;
}
}
但是现在我想显示每封邮件的用户名(来自users
集合)。
我通常称其为客户端联接,尽管我不确定Flutter是否为其指定名称。
我已经找到了一种执行此操作的方法(我在下面发布了此方法),但是想知道在Flutter中是否有另一种/更好/更惯用的方法来进行这种操作。
那么:在Flutter中,惯用的方式是如何在上述结构中查找每条消息的用户名?
答案 0 :(得分:3)
我可以使用另一个版本,该版本似乎比my answer with the two nested builders更好。
这里,我使用专用的Message
类来保存来自消息Document
和可选的关联用户Document
的信息,从而以自定义方法隔离了数据加载。
class Message {
final message;
final timestamp;
final uid;
final user;
const Message(this.message, this.timestamp, this.uid, this.user);
}
class ChatList extends StatelessWidget {
Stream<List<Message>> getData() async* {
var messagesStream = Firestore.instance.collection("chat").orderBy("timestamp", descending: true).snapshots();
var messages = List<Message>();
await for (var messagesSnapshot in messagesStream) {
for (var messageDoc in messagesSnapshot.documents) {
var message;
if (messageDoc["uid"] != null) {
var userSnapshot = await Firestore.instance.collection("users").document(messageDoc["uid"]).get();
message = Message(messageDoc["message"], messageDoc["timestamp"], messageDoc["uid"], userSnapshot["name"]);
}
else {
message = Message(messageDoc["message"], messageDoc["timestamp"], "", "");
}
messages.add(message);
}
yield messages;
}
}
@override
Widget build(BuildContext context) {
var streamBuilder = StreamBuilder<List<Message>>(
stream: getData(),
builder: (BuildContext context, AsyncSnapshot<List<Message>> messagesSnapshot) {
if (messagesSnapshot.hasError)
return new Text('Error: ${messagesSnapshot.error}');
switch (messagesSnapshot.connectionState) {
case ConnectionState.waiting: return new Text("Loading...");
default:
return new ListView(
children: messagesSnapshot.data.map((Message msg) {
return new ListTile(
title: new Text(msg.message),
subtitle: new Text(DateTime.fromMillisecondsSinceEpoch(msg.timestamp).toString()
+"\n"+(msg.user ?? msg.uid)),
);
}).toList()
);
}
}
);
return streamBuilder;
}
}
与solution with nested builders相比,此代码更具可读性,主要是因为数据处理和UI构建器更好地分开了。它还仅为发布消息的用户加载用户文档。不幸的是,如果用户发布了多条消息,它将为每条消息加载文档。我可以添加一个缓存,但是认为这段代码已经完成了一些工作。
答案 1 :(得分:3)
您可以使用RxDart这样操作。.https://pub.dev/packages/rxdart
import 'package:rxdart/rxdart.dart';
class Messages {
final String messages;
final DateTime timestamp;
final String uid;
final DocumentReference reference;
Messages.fromMap(Map<String, dynamic> map, {this.reference})
: messages = map['messages'],
timestamp = (map['timestamp'] as Timestamp)?.toDate(),
uid = map['uid'];
Messages.fromSnapshot(DocumentSnapshot snapshot)
: this.fromMap(snapshot.data, reference: snapshot.reference);
@override
String toString() {
return 'Messages{messages: $messages, timestamp: $timestamp, uid: $uid, reference: $reference}';
}
}
class Users {
final String name;
final DocumentReference reference;
Users.fromMap(Map<String, dynamic> map, {this.reference})
: name = map['name'];
Users.fromSnapshot(DocumentSnapshot snapshot)
: this.fromMap(snapshot.data, reference: snapshot.reference);
@override
String toString() {
return 'Users{name: $name, reference: $reference}';
}
}
class CombineStream {
final Messages messages;
final Users users;
CombineStream(this.messages, this.users);
}
Stream<List<CombineStream>> _combineStream;
@override
void initState() {
super.initState();
_combineStream = Observable(Firestore.instance
.collection('chat')
.orderBy("timestamp", descending: true)
.snapshots())
.map((convert) {
return convert.documents.map((f) {
Stream<Messages> messages = Observable.just(f)
.map<Messages>((document) => Messages.fromSnapshot(document));
Stream<Users> user = Firestore.instance
.collection("users")
.document(f.data['uid'])
.snapshots()
.map<Users>((document) => Users.fromSnapshot(document));
return Observable.combineLatest2(
messages, user, (messages, user) => CombineStream(messages, user));
});
}).switchMap((observables) {
return observables.length > 0
? Observable.combineLatestList(observables)
: Observable.just([]);
})
}
答案 2 :(得分:2)
如果我正确地阅读了此内容,则问题将抽象为:如何转换需要进行异步调用以修改流中数据的数据流?
在问题的上下文中,数据流是消息的列表,异步调用是获取用户数据并使用流中的此数据更新消息。
可以使用asyncMap()
函数在Dart流对象中直接执行此操作。这是一些演示如何实现的纯Dart代码:
import 'dart:async';
import 'dart:math' show Random;
final random = Random();
const messageList = [
{
'message': 'Message 1',
'timestamp': 1,
'uid': 1,
},
{
'message': 'Message 2',
'timestamp': 2,
'uid': 2,
},
{
'message': 'Message 3',
'timestamp': 3,
'uid': 2,
},
];
const userList = {
1: 'User 1',
2: 'User 2',
3: 'User 3',
};
class Message {
final String message;
final int timestamp;
final int uid;
final String user;
const Message(this.message, this.timestamp, this.uid, this.user);
@override
String toString() => '$user => $message';
}
// Mimic a stream of a list of messages
Stream<List<Map<String, dynamic>>> getServerMessagesMock() async* {
yield messageList;
while (true) {
await Future.delayed(Duration(seconds: random.nextInt(3) + 1));
yield messageList;
}
}
// Mimic asynchronously fetching a user
Future<String> userMock(int uid) => userList.containsKey(uid)
? Future.delayed(
Duration(milliseconds: 100 + random.nextInt(100)),
() => userList[uid],
)
: Future.value(null);
// Transform the contents of a stream asynchronously
Stream<List<Message>> getMessagesStream() => getServerMessagesMock()
.asyncMap<List<Message>>((messageList) => Future.wait(
messageList.map<Future<Message>>(
(m) async => Message(
m['message'],
m['timestamp'],
m['uid'],
await userMock(m['uid']),
),
),
));
void main() async {
print('Streams with async transforms test');
await for (var messages in getMessagesStream()) {
messages.forEach(print);
}
}
大多数代码都将来自Firebase的数据模拟为消息映射流,并具有异步功能来获取用户数据。这里的重要功能是getMessagesStream()
。
由于它是流中出现的消息列表,因此代码有些复杂。为了防止调用获取用户数据的同步发生,该代码使用Future.wait()
来收集List<Future<Message>>
并在所有期货都完成后创建一个List<Message>
。
在Flutter中,您可以在getMessagesStream()
中使用来自FutureBuilder
的流来显示消息对象。
答案 3 :(得分:1)
理想情况下,您希望排除任何业务逻辑,例如将数据加载到单独的服务中或遵循BloC模式,例如:
class ChatBloc {
final Firestore firestore = Firestore.instance;
final Map<String, String> userMap = HashMap<String, String>();
Stream<List<Message>> get messages async* {
final messagesStream = Firestore.instance.collection('chat').orderBy('timestamp', descending: true).snapshots();
var messages = List<Message>();
await for (var messagesSnapshot in messagesStream) {
for (var messageDoc in messagesSnapshot.documents) {
final userUid = messageDoc['uid'];
var message;
if (userUid != null) {
// get user data if not in map
if (userMap.containsKey(userUid)) {
message = Message(messageDoc['message'], messageDoc['timestamp'], userUid, userMap[userUid]);
} else {
final userSnapshot = await Firestore.instance.collection('users').document(userUid).get();
message = Message(messageDoc['message'], messageDoc['timestamp'], userUid, userSnapshot['name']);
// add entry to map
userMap[userUid] = userSnapshot['name'];
}
} else {
message =
Message(messageDoc['message'], messageDoc['timestamp'], '', '');
}
messages.add(message);
}
yield messages;
}
}
}
然后,您可以仅在组件中使用Bloc并收听chatBloc.messages
流。
class ChatList extends StatelessWidget {
final ChatBloc chatBloc = ChatBloc();
@override
Widget build(BuildContext context) {
return StreamBuilder<List<Message>>(
stream: chatBloc.messages,
builder: (BuildContext context, AsyncSnapshot<List<Message>> messagesSnapshot) {
if (messagesSnapshot.hasError)
return new Text('Error: ${messagesSnapshot.error}');
switch (messagesSnapshot.connectionState) {
case ConnectionState.waiting:
return new Text('Loading...');
default:
return new ListView(children: messagesSnapshot.data.map((Message msg) {
return new ListTile(
title: new Text(msg.message),
subtitle: new Text('${msg.timestamp}\n${(msg.user ?? msg.uid)}'),
);
}).toList());
}
});
}
}
答案 4 :(得分:1)
允许我提出我的RxDart解决方案版本。我使用combineLatest2
和ListView.builder
来构建每个消息小部件。在构造每个消息小部件的过程中,我用相应的uid
查找用户的名称。
在此代码段中,我对用户名使用了线性查找,但是可以通过创建uid -> user name
映射来改进
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/widgets.dart';
import 'package:rxdart/rxdart.dart';
class MessageWidget extends StatelessWidget {
// final chatStream = Firestore.instance.collection('chat').snapshots();
// final userStream = Firestore.instance.collection('users').snapshots();
Stream<QuerySnapshot> chatStream;
Stream<QuerySnapshot> userStream;
MessageWidget(this.chatStream, this.userStream);
@override
Widget build(BuildContext context) {
Observable<List<QuerySnapshot>> combinedStream = Observable.combineLatest2(
chatStream, userStream, (messages, users) => [messages, users]);
return StreamBuilder(
stream: combinedStream,
builder: (_, AsyncSnapshot<List<QuerySnapshot>> snapshots) {
if (snapshots.hasData) {
List<DocumentSnapshot> chats = snapshots.data[0].documents;
// It would be more efficient to convert this list of user documents
// to a map keyed on the uid which will allow quicker user lookup.
List<DocumentSnapshot> users = snapshots.data[1].documents;
return ListView.builder(itemBuilder: (_, index) {
return Center(
child: Column(
children: <Widget>[
Text(chats[index]['message']),
Text(getUserName(users, chats[index]['uid'])),
],
),
);
});
} else {
return Text('loading...');
}
});
}
// This does a linear search through the list of users. However a map
// could be used to make the finding of the user's name more efficient.
String getUserName(List<DocumentSnapshot> users, String uid) {
for (final user in users) {
if (user['uid'] == uid) {
return user['name'];
}
}
return 'unknown';
}
}
答案 5 :(得分:0)
我工作的第一个解决方案是嵌套两个StreamBuilder
实例,每个集合/查询一个实例。
class ChatList extends StatelessWidget {
@override
Widget build(BuildContext context) {
var messagesSnapshot = Firestore.instance.collection("chat").orderBy("timestamp", descending: true).snapshots();
var usersSnapshot = Firestore.instance.collection("users").snapshots();
var streamBuilder = StreamBuilder<QuerySnapshot>(
stream: messagesSnapshot,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> messagesSnapshot) {
return StreamBuilder(
stream: usersSnapshot,
builder: (context, usersSnapshot) {
if (messagesSnapshot.hasError || usersSnapshot.hasError || !usersSnapshot.hasData)
return new Text('Error: ${messagesSnapshot.error}, ${usersSnapshot.error}');
switch (messagesSnapshot.connectionState) {
case ConnectionState.waiting: return new Text("Loading...");
default:
return new ListView(
children: messagesSnapshot.data.documents.map((DocumentSnapshot doc) {
var user = "";
if (doc['uid'] != null && usersSnapshot.data != null) {
user = doc['uid'];
print('Looking for user $user');
user = usersSnapshot.data.documents.firstWhere((userDoc) => userDoc.documentID == user).data["name"];
}
return new ListTile(
title: new Text(doc['message']),
subtitle: new Text(DateTime.fromMillisecondsSinceEpoch(doc['timestamp']).toString()
+"\n"+user),
);
}).toList()
);
}
});
}
);
return streamBuilder;
}
}
正如我的问题中所述,我知道这种解决方案虽然不好,但至少可以奏效。
我看到一些问题:
如果您知道更好的解决方案,请发布答案。