Flutter 转换流<;列表<;字符串>&燃气轮机;列出<;字符串>;飘飘然

Flutter 转换流<;列表<;字符串>&燃气轮机;列出<;字符串>;飘飘然,flutter,dart,Flutter,Dart,我正在尝试在flift中将流转换为List 这是我的密码 Stream<List<String>> _currentEntries; /// A stream of entries that should be displayed on the home screen. Stream<List<String>> get categoryEntries => _currentEntries; 我得到以下错误: 无法从方法categoryLi

我正在尝试在flift中将
流转换为List
这是我的密码

Stream<List<String>> _currentEntries;

/// A stream of entries that should be displayed on the home screen.
Stream<List<String>> get categoryEntries => _currentEntries;
我得到以下错误:

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


是否有人可以帮助您解决此问题并转换
流问题似乎与
类别列表的返回类型有关。当
仅包含一层
列表
时,您将以
列表
返回。返回类型应为
Future

使用
.first
.last
.single
以及
等待
仅获取单个元素,并且应删除
toList()

Future<List<String>> categoryList () async  {
  return await _currentEntries.first;
}
Future categoryList()异步{
返回等待_currentEntries.first;
}

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

您只能将
转换为
未来
,因为您无法将异步转换为同步。

我不知道流可以等待来自服务器,在我的例子中,我使用BLOC模式并使用
Future-getCategoryList-async(){…}
来获取我将使用的列表,如下所示:

Future<List<String>> getCategory() async {
    var result = await http.get();
    //Some format and casting code for the String type here
    return result;
}
Future getCategory()异步{
var result=wait http.get();
//这里有一些字符串类型的格式和强制转换代码
返回结果;
}

希望这个帮助

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

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

您可以使用流上的
listen()
方法获取任何值并处理它(“转换它”)。你也可以检查这个写得很好的介质。干杯

 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);
    }
 });
Stream\u currentEntries=watchForSomeStream();
_currentEntries.listen((ListOfstring){
//从这一点上,您可以使用listofstring作为列表对象
//并执行您想要的所有其他业务逻辑
for(ListOfstring中的字符串myString){
打印(myString);
}
});

您能否共享从数据库返回的数据以及如何格式化数据?@SanjaySharma问题中解释了数据库中的数据类型。嗨,克里斯托弗,谢谢您的回答。我面临的一个小问题是,我调用categoryList函数并将其分配给一个列表,如List lit=bloc.categoryList();这产生了一个错误:不能将future的值分配给变量列表。我怎样才能解决这个问题?@yoohoo你必须等待未来。所以do
List lit=wait bloc.categoryList()此解决方案非常适合转换。
 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);
    }
 });