snapshot.hasData总是返回false

时间:2019-05-06 04:31:56

标签: android ios dart flutter

我尝试从api https://location-query.herokuapp.com/location?key_word=ha%20noi

获取数据

这是响应json:

{  
   "code":200,
   "key_word":"ha noi",
   "result":[  
      {  
         "id":1581130,
         "name":"Ha Noi",
         "country":"VN",
         "coord":{  
            "lon":105.841171,
            "lat":21.0245
         }
      }
   ]
}

这是我的数据类:

class Coord {
  final double lon, lat;

  Coord({this.lon, this.lat});

  factory Coord.fromJson(Map<String, dynamic> json) {
    return Coord(
      lon: json['lon'],
      lat: json['lat']
    );
  }
}

class Location {
  final int id;
  final String name, country;
  final Coord coord;

  Location({this.id, this.name, this.country, this.coord});

  factory Location.fromJson(Map<String, dynamic> json) {
    return Location(
      id: json['id'],
      name: json['name'],
      country: json['country'],
      coord: Coord.fromJson(json['coord'])
    );
  }
}

class Locations {
  final int code;
  final String key_word;
  final List<Location> result;

  Locations({this.code, this.key_word, this.result});

  factory Locations.fromJson(Map<String, dynamic> json) {
    return Locations(
        code: json['code'],
        key_word: json['key_word'],
        result: json['result'].map((value) => Location.fromJson(value)).toList()
    );
  }
}

这是我的请求类别:

class SearchLocation {

  Future<Locations> search(key_word) async {
    final get = await http.get(Api().searchLocation(key_word));
    if (get.statusCode == 200)
      return Locations.fromJson(json.decode(get.body));
    else
      throw Exception('Can not request');
  }

}

这是代码可以读取数据的代码,但是snapshot.hasData总是返回false:

SearchLocation searchLocation = SearchLocation();
_searchResult = searchLocation.search(_controller.text);

FutureBuilder<Locations>(
                future: _searchResult,
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    return Text('Done');
                  }
                  else {
                    print('Location: No Result');
                    return Text('No result');
                  }
                })

1 个答案:

答案 0 :(得分:0)

您可以尝试替换下面的代码:

FutureBuilder<Locations>(
        future: search(_controller.text),
        builder: (context, snapshot) {
          if(snapshot.connectionState == ConnectionState.done){
            return Text('Done');
          }else {
            print('Location: No Result');
            return Text('No result');
          }
        });

位置模型类别

class Locations {
  final int code;
  final String key_word;
  final List<Location> result;

  Locations({this.code, this.key_word, this.result});

  factory Locations.fromJson(Map<String, dynamic> json) {
    return Locations(
        code: json['code'],
        key_word: json['key_word'],
        result: (json['result'] as List).map((value) => Location.fromJson(value)).toList()
    );
  }
}

如果需要更多信息,请告诉我。