我想从服务器获取数据,然后解析json。完成后,我想导航到另一个 View 。

  void getServerData() async{

   WebRequests ws = WebRequests('https://sampleurl');

   Map<String, dynamic> map = await ws.getData();

   mychamplist = map['mychampionships'];



mychamplist.forEach((f){
  mychampionships.add(MyChampionships(
    name: f['name'],
    id: int.parse(f['id']),
    numberOfPlayers: int.parse(f['nofplayers']),
  ));
});

Navigator
    .of(context)
    .pushReplacement(new MaterialPageRoute(builder: (BuildContext context) {
  return FantasyNbi();
}));
 }

在上一个代码完成之前,它将导航到FantasyNbi类。

它如何以适当的方式来做?

最佳答案

我为您提供了一个示例类,您可以使用:

class API {
  static Future getData(String url) {

    return http.get('api link' + url);
  }

  static Future<List<BasicDiskInfo>> fetchAllDisks() async {
    final response = await getData('disk');

    if (response.statusCode == 200) {
      Iterable list = json.decode(response.body);
      List<BasicDiskInfo> disks =
          list.map((model) => BasicDiskInfo.fromJson(model)).toList();
      return disks;
    } else {
      throw Exception('Failed to load disks');
    }
  }

  static Future<Disk> fetchDisk(int id) async {
    final response = await getData('disk/' + id.toString());

    if (response.statusCode == 200) {
      return Disk.fromJson(json.decode(response.body));
    } else {
      throw Exception('Failed to load disk');
    }
  }
}

class Disk {
  int id;
  String name;
  String volumeLable;
  bool isReady;
  String driveType;
  String driveFormat;
  int totalSize;
  int totalFreeSpace;
  int availableFreeSpace;

  Disk(
      {this.id,
      this.name,
      this.volumeLable,
      this.isReady,
      this.driveType,
      this.driveFormat,
      this.totalSize,
      this.totalFreeSpace,
      this.availableFreeSpace});

  factory Disk.fromJson(Map<String, dynamic> json) {
    return Disk(
        id: json['id'],
        name: json['name'],
        volumeLable: json['volumeLable'],
        isReady: json['isReady'],
        driveType: json['driveType'],
        driveFormat: json['driveFormat'],
        totalSize: json['totalSize'],
        totalFreeSpace: json['totalFreeSpace'],
        availableFreeSpace: json['availableFreeSpace']);
  }
}

为了获取数据,我可以这样做:

  var data = await API.fetchAllDisks();
  // or
  API.fetchAllDisks().then((response) => {/* do something */})

关于dart - Web请求后,导航到其他 View (异步/等待正确使用)-Flutter和dart,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56256288/

10-10 17:55