【问题标题】:Dart filter stream list using closureDart 使用闭包过滤流列表
【发布时间】:2020-09-28 19:21:40
【问题描述】:

我有一个 Firestore 记录列表作为流。我想将记录的 uid 传递给列表并返回下一项。

用户名 -----|------------- 001 |史蒂夫 002 |大卫 003 |标记 004 |乔治 ------------------

如果我通过 uid 001 方法应该返回 002 | 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();
  }
}

我试过这段代码,但它抛出错误。

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;
  }

【问题讨论】:

  • 您需要await 拨打id.then
  • 我需要将项目作为流返回。如果我使用 await,我需要使方法 async 不适用于流。
  • 现在id 是一个未来。您别无选择,只能await 或提出完全不同的解决方案。
  • 必须有一种方法可以在不使用 Future 的情况下实现这一点。
  • 您正在使用流。流本质上是异步结构。因此,调用first 是一个异步操作,因此它返回一个未来。虽然可能有办法绕过这一点并同步获取数据,但它们几乎都可以保证是反模式并导致脆弱、复杂和高度耦合的解决方案。相反,最好先问问为什么需要同步获取这些数据,以及使用流是否适合这个应用程序。

标签: flutter dart stream


【解决方案1】:

好的,这似乎可行。不确定这是否是最佳解决方案。

 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));
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-26
    • 2013-08-02
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多