Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

firebase - Search feature Stream refactoring

  SearchService().searchByName(value, context).then((QuerySnapshot docs) {

I'm trying to refactor this as I've changed SearchService() to a Stream.

.then gives, of course, The method '.then' isn't defined for the type 'Stream'.

A very 'novice' quesiton, but I'm not sure the correct way to rewrite this for a Stream?

if (queryResultSet.length == 0 && value.length == 1) {
  SearchService().searchByName(value, context).then((QuerySnapshot docs) {
    for (int i = 0; i < docs.docs.length; ++i) {
      queryResultSet.add(docs.docs[i].data());
    }
  });

.

class SearchService {
Stream<QuerySnapshot> searchByName(
  String searchField, BuildContext context) async* {
final uid = await TheProvider.of(context).auth.getCurrentUID();
yield* FirebaseFirestore.instance
    .collection("userData")
    .doc(uid)
    .collection("Contacts")
    .where('searchKey',
        isEqualTo: searchField.substring(0, 1).toUpperCase())
    .snapshots();
}
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want a single result from a database query instead of a stream of results that change over time, use get() instead of snapshots(). It will return a Future that works the way you expect. This is illustrated in the documentation.

FirebaseFirestore.instance
    .collection("userData")
    .doc(uid)
    .collection("Contacts")
    .where('searchKey',
        isEqualTo: searchField.substring(0, 1).toUpperCase())
    .get();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...