簡體   English   中英

如何擺脫“未來”的實例<dynamic> &#39; 在顫振/飛鏢中?

[英]how to get rid of Instance of 'Future<dynamic>' in Flutter/dart?

我有以下代碼

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

main(){
  var list = logic();
  removeOne(list);
}


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;
}

removeOne(aList){
  aList.removeLast();
  print(aList);
}

當我運行它時,我收到以下錯誤。

Unhandled exception:
NoSuchMethodError: Class 'Future<dynamic>' has no instance method 'removeLast'.
Receiver: Instance of 'Future<dynamic>'
Tried calling: removeLast()
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1      removeOne (file:///Users/macpro/Desktop/minimaltube/logic.dart:23:9)
#2      main (file:///Users/macpro/Desktop/minimaltube/logic.dart:7:3)
#3      _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:305:19)
#4      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:172:12)

如何擺脫var list'Future<dynamic>' 我希望它成為一個 var 以便我以后可以訪問它,以便removeOne(list)可以完成它的工作。

main() async {

List<String> list = await logic<String>();
removeOne(list);

}


Future<List<T>>logic<T>() 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;
}

removeOne(aList){
  aList.removeLast();
  print(aList);
}

future 還沒有解析,必須先解析,這樣才能將返回的數據作為列表使用。

編譯器在您的 main 方法中逐步執行,在解決未來(仍然是未來)之前,將其分配給變量列表,然后當我們將該未來傳遞給函數“removeOne(list)”時移動到下一行”。

您可以做些什么來解決您的未來,在函數調用之后添加一個 .then() 以便它等待未來,當它到來時,將其轉換為您想要的數據類型。

將 main 中的代碼替換如下:

logic().then((list) => removeOne(list));

或者,您可以采用另一種方法讓您的完整 main 方法異步,這是有爭議的,有人說這不是一個好的做法。 這將如下所示:

main() async {
 var list = await logic();
 removeOne(list);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM