Flutter 转换流<;列表<;字符串>&燃气轮机;列出<;字符串>;飘飘然
我正在尝试在flift中将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
流转换为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你必须等待未来。所以doList 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);
}
});