在颤动列表中使用将来的对象的数据

问题描述 投票:0回答:2
  @override
  void initState() {
    super.initState();
    futureInfo = fetchInfo();
  }

  Future<Info> futureInfo;
  List<String> prices = [];
  List<String> duration = ["11 hours", "14 hours", "15 hours","12 hours", "10 hours", "8 hours",];
  List<String> airline = ["Middle East Airline", "Air Canada Airline", "Turkish Airline","Middle east Airline", "Turkish Airline", "Air Canada Airline",];
  List<String> destination = ['Beirut','Madrid'];

你好我还是很陌生,我只想知道如何使用价格列表中Future对象FutureInfo中的数据,其中futureInfo是将Json文件解析为我拥有的类,并且我想能够访问它的属性。您还可以带我参考任何文档或视频,这些文档或视频可以帮助我学习Flutter / dart的更多技术部分,而不是更多UI内容。(例如:函数,状态,变量...)

这是Info对象

class Info {
  Meta meta;
  List<Datum> data;
  Dictionaries dictionaries;

  Info({
    this.meta,
    this.data,
    this.dictionaries,
  });

  factory Info.fromJson(Map<String, dynamic> json) => Info(
    meta: Meta.fromJson(json["meta"]),
    data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
    dictionaries: Dictionaries.fromJson(json["dictionaries"]),
  );

  Map<String, dynamic> toJson() => {
    "meta": meta.toJson(),
    "data": List<dynamic>.from(data.map((x) => x.toJson())),
    "dictionaries": dictionaries.toJson(),
  };
}

这是我的功能,它从rest API获取对象的信息:

Future<Info> fetchInfo() async {
 final response =
 await http.get(
     Uri.encodeFull("https://test.api.amadeus.com/v2/shopping/flight-offers?originLocationCode=SYD&destinationLocationCode=BKK&departureDate=2020-08-01&returnDate=2020-08-05&adults=2&includedAirlineCodes=TG&max=3"),
     headers: {
       "Authorization" : "Bearer ###############"
     });
 if (response.statusCode == 200) {
   // If the server did return a 200 OK response, then parse the JSON.

   return Info.fromJson(json.decode(response.body));
 } else {
   // If the server did not return a 200 OK response, then throw an exception.
   throw Exception('Failed to load');
 }
}
list flutter dart future
2个回答
1
投票

我建议您放置信息对象

信息信息;

而不是

Future futureInfo;

,然后使您的fetchInfo()方法像这样异步,

fetchInfo()async{
//inside async method you can wait for any future to complete using await keywork

await operation1;
await operation2;

//then setState your Info object
setState(() {
  this.info = newValue;
});


}

请张贴完整的代码,以使其更加清晰。请更容易。


0
投票

为了了解未来,您应该阅读以下内容:https://dart.dev/codelabs/async-await

如果您是新手,那么我建议您通过此操作进行Http呼叫:https://flutter.dev/docs/cookbook/networking/fetch-data

否则,我会请您跟随Bloc库获取有关处理状态更改的深入知识。 Bloc库在这里:https://bloclibrary.dev/

© www.soinside.com 2019 - 2024. All rights reserved.