简体   繁体   English

如何在flutter中将Future List实例转换为List String

[英]How to convert Future List instance to List String in flutter

I am saving strings list in shared procedure and fetching that like below我正在共享过程中保存字符串列表并获取如下所示的内容

Future<List<String>> getList() async {
  final prefs = await SharedPreferences.getInstance();
  return prefs.getStringList("key");
}

Issue is that I need to send that list to server but facing issue as I need to convert that future list to simple List问题是我需要将该列表发送到服务器但面临问题,因为我需要将该未来列表转换为简单列表

How can I do that?我怎样才能做到这一点? or is there any other way as I need to send list of ids save by user to server.或者有没有其他方法,因为我需要将用户保存的 id 列表发送到服务器。

When you mark a function as async it will return a future .当您将函数标记为async 时,它将返回一个 future

If you dont wait for the future you will get ' Future instance ' this means your future(data) is not available yet.如果您不等待未来,您将获得“未来实例”,这意味着您的未来(数据)尚不可用。

If you want to wait for the future(data) to be resolved you need to use the await keyword.如果你想等待未来(数据)被解析,你需要使用await关键字。

So in your case you can create a List<String> myList;因此,在您的情况下,您可以创建一个List<String> myList; then create a function to wait for the future and assign the data to the previous List.然后创建一个等待未来的函数,并将数据分配给之前的列表。

List<String> myList;
void getStringList() async {
var tempList = await getList();
// Or use setState to assign the tempList to myList
myList = tempList;
}

Or use Then :或者使用Then

getList().then(List<String> myList {
// TODO: Send myList to server.
});

Hope this helpe!!希望这有帮助!!

When you work with async data you should "wait" while data will not completely loaded.当您使用异步数据时,您应该“等待”数据未完全加载。 You can use await word in async methods like that:您可以在这样的异步方法中使用await word:

foo() async {
  final Future<List<dynamic>> futureList = fetchSomeFutureList();
  final list = await futureList;
}

or use Future's then() method to delegate some work.或者使用 Future 的then()方法来委派一些工作。 You also can wait for futures in widget tree using FutureBuilder .您还可以使用FutureBuilder在小部件树中等待期货。 Check Dart Docs page for see details.查看Dart 文档页面以了解详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM