在 flutter 中将 Stream<List<String>> 转换为 List<String>

yoo*_*hoo 13 dart flutter

我正在尝试将 a 转换Stream<List<String>> to List<String>为 flutter 这是我的代码

Stream<List<String>> _currentEntries;

/// A stream of entries that should be displayed on the home screen.
Stream<List<String>> get categoryEntries => _currentEntries;
Run Code Online (Sandbox Code Playgroud)

_currentEntries正在使用数据库中的数据进行填充。我想转换_currentEntriesList<String>

我尝试了以下代码但不起作用:

List<List<String>> categoryList () async  {
  return await _currentEntries.toList();
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

List<List<String>>无法从方法返回type 的值,categoryList因为它的返回类型为List<List<String>>

有人可以帮助如何解决这个问题并将 a 转换Stream<List<String>为 吗List<String>

Chr*_*ore 10

问题似乎与您的返回类型有关categoryList。当only 包含单层时,您List将从s返回。返回类型应该是.ListStreamListFuture<List<String>>

使用.first.last.singleawait获取单个元素,并且toList()应该将其删除。

Future<List<String>> categoryList () async  {
  return await _currentEntries.first;
}
Run Code Online (Sandbox Code Playgroud)

还有一个快速提示:Dart 会自动为所有字段生成 getter 和 setter,因此您显示的 getter 方法不是必需的。


小智 6

正如标题所说,问题是如何将某些项目的流转换为项目。所以 Christopher 的回答是可以的,但前提是你想从流中获取第一个值。由于流是异步的,它们可以在任何时间点为您提供值,您应该处理流中的所有事件(而不仅仅是第一个事件)。

假设您正在观看数据库中的流。每次数据库数据修改时,您都会从数据库收到新值,这样您就可以根据新收到的值自动更新 GUI。但如果您只从流中获取第一个值,则不会,它只会在第一次更新。

您可以使用listen()流上的方法获取任何值并处理它(“转换它”)。您也可以在 Medium 上查看这篇写得很好的教程。干杯!

 Stream<List<String>> _currentEntries = watchForSomeStream();

 _currentEntries.listen((listOfStrings) {
    // From this point you can use listOfStrings as List<String> object
    // and do all other business logic you want

    for (String myString in listOfStrings) {
      print(myString);
    }
 });
Run Code Online (Sandbox Code Playgroud)