简体   繁体   中英

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.

UPDATE: To better illustrate the problem with the IDE. 在此处输入图片说明

Use async await.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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