简体   繁体   English

我如何存储 Future<dynamic> 稍后在 dart/Flutter 中的程序中使用的数据?

[英]How can I store a Future <dynamic> data for later use within a program in dart/Flutter?

I have the following code that does not work:我有以下代码不起作用:

import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:async';


main(){
  String firstTitle = "";
  firstTitle = logic().then((list) => getFirstTitle(list)); // I want to store this data into the variable 
// firstTitle for later use. 
// However my IDE does not recognize the second firstTitle as being linked to the declaration String firstTitle.

}

class MyList {
  static var list = [1];
}

logic() async{
  final result = await http.get('https://invidio.us/api/v1/search?q=tech+lead');
  final data = json.decode(result.body);
  final myList = [];
  data.forEach((e) {    
    myList.add({"title": e['title'], 'videoId': e['videoId'], 'duration': e['lengthSeconds'], "date": e['publishedText']});
    //print(myList);
  });
  return myList;
}



String getFirstTitle(aList){
  return aList[0]["title"];
}

I understand that we await for the data to be fetched from the source but once it is how can I keep as any variable ex: String instead of having it as a Future.我知道我们在等待从源中获取数据,但是一旦它成为任何变量,例如:String,而不是将其作为 Future。

UPDATE: To better illustrate the problem with the IDE.更新:为了更好地说明 IDE 的问题。 在此处输入图片说明

Use async await.使用异步等待。

main() async {
  String firstTitle = "";
  List list=[];
  list=await logic();
  firstTitle = getFirstTitle(list));
}

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

相关问题 如何在循环中使用 Future/Async function? (飞镖/颤振) - how can I use Future/Async function in a loop? (dart/flutter) 如何在 Dart/Flutter 中重试 Future? - How can I retry a Future in Dart/Flutter? 如何将新数据添加到 Future<dynamic> 在 dart / flutter?</dynamic> - How to add new data into Future<dynamic> in dart / flutter? 如何改变未来<dynamic>串入 dart:flutter</dynamic> - how to transform a Future<dynamic> to string in dart:flutter 使用Flutter和Dart,如何使Future正常工作? - Using Flutter and Dart, how can I get this Future to work? 如何在加载应用程序时存储未来数据以供进一步使用? # Flutter - how to store future data while loading app for further use ? # Flutter Flutter/Dart - 在 Future 中使用 ChangeNotifier 或 setState 之类的东西? - Flutter/Dart - Use something like ChangeNotifier or setState within Future? 如何摆脱“未来”的实例<dynamic> &#39; 在颤振/飞镖中? - how to get rid of Instance of 'Future<dynamic>' in Flutter/dart? 使用 Dart 和 Flutter,如何将动态小部件中的数据保存到另一个列表内的地图列表中 - Using Dart and Flutter, how can I save data from a dynamic widget, into a list of maps, that is inside of another list 我无法从未来函数中的列表中取出数据。 颤动/飞镖 - I can't take out data from list inside future function. Flutter/Dart
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM