使用闭包的Dart过滤器流列表 [英] Dart filter stream list using closure

查看:197
本文介绍了使用闭包的Dart过滤器流列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一份流存储的Firestore记录列表。我想将记录的uid传递到列表中并返回下一个项目。

I have a list of firestore records as stream. I want to pass uid of a record to the list and return next item.


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

如果我通过uid 001 该方法应返回 002 | David 并传递001或004应该返回null。

If I pass uid 001 the method should return 002 | David and passing 001 or 004 should return 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));
  }

这篇关于使用闭包的Dart过滤器流列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆