Reputation: 688
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.
Upvotes: 1
Views: 406
Reputation: 4124
Use async await.
main() async {
String firstTitle = "";
List list=[];
list=await logic();
firstTitle = getFirstTitle(list));
}
Upvotes: 1