简体   繁体   English

使用闭包的 Dart 过滤流列表

[英]Dart filter stream list using closure

I have a list of firestore records as stream.我有一个 Firestore 记录列表作为流。 I want to pass uid of a record to the list and return next item.我想将记录的 uid 传递给列表并返回下一项。

uid     name
-----|-------------
001  | Steve
002  | David
003  | Mark
004  | George
-------------------

If I pass uid 001 the method should return 002 |如果我传递 uid 001,则该方法应返回002 | David and passing 001 or 004 should return null. David并通过 001 或 004 应该返回 null。

class SearchResultsBloc implements BlocBase {
  SearchResultsBloc() {
    DatabaseService().Search().listen((data) => _inList.add(data));
  }

  final _listController = BehaviorSubject<List<Profile>>();
  Stream<List<Profile>> get outList => _listController.stream;
  Sink<List<Profile>> get _inList => _listController.sink;

  Stream<Profile> nextProfile(String uid) {
    var id = outList
        .map<int>(
            (results) => results.indexWhere((profile) => profile.uid == uid))
        .first;

    Stream<Profile> profile = id.then((index) {
      return outList.map<Profile>((results) => results.elementAt(index));
    });

    return profile;
  }


  @override
  void dispose() {
    _listController.close();
  }
}

I've tried this code but it's throwing error.我试过这段代码,但它抛出错误。

A value of type 'Future<Stream<Profile>>' can't be assigned to a variable of type 'Stream<Profile>'.

  Stream<Profile> nextProfile(String uid) {
    var id = outList
        .map<int>(
            (results) => results.indexWhere((profile) => profile.uid == uid))
        .first;

    Stream<Profile> profile = id.then((index) {
      return outList.map<Profile>((results) => results.elementAt(index));
    });

    return profile;
  }

Okay, this seems to work.好的,这似乎有效。 Not sure whether this is the best solution.不确定这是否是最佳解决方案。

 Stream<Profile> nextProfile(String uid) {
    var index = outList
        .map<int>(
            (results) => results.indexWhere((profile) => profile.uid == uid))
        .first
        .asStream();

    int nextIndex;
    index.listen((index) {
      nextIndex = index + 1;
    });

    return outList.map<Profile>((results) => results.elementAt(nextIndex));
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM