• 主页
  • 来自快速Api的Flutter http请求未加载

来自快速Api的Flutter http请求未加载

我使用Dart的http包从Rapid api上的Api检索数据,并使用Flutter显示它,但是内容从未加载,api也没有返回错误。

class APIService {
  // API key
  static const _api_key = <MYAPIKEY>;
  // Base API url
  static const String _baseUrl = "covid-19-data.p.rapidapi.com";
  // Base headers for Response url
  static const Map<String, String> _headers = {
    "content-type": "application/json",
    "x-rapidapi-host": "covid-19-data.p.rapidapi.com",
    "x-rapidapi-key": _api_key,
  };

  Future<CovidNumbers> fetchData(
      {@required String endpoint, @required Map<String, String> query}) async {
    Uri uri = Uri.https(_baseUrl, endpoint, query);

    final response = await http.get(uri, headers: _headers);
    if (response.statusCode == 200) {
      return CovidNumbers.fromJson(json.decode(response.body));
    } else {
      throw Exception('Failed to load Data');
    }
  }
}

该方法随后被称为onInit

  Future<CovidNumbers> data;
  APIService apiService = APIService();

  @override
  void initState() {
    super.initState();
    data = apiService.fetchData(
        endpoint: "/country", query: {"format": "json", "name": "malta"});
  }

最后,我将其显示在FutureBuilder中

FutureBuilder<CovidNumbers>(
          //future: futureCovidNumbers,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return Text(
                  "Confirmed Cases: ${snapshot.data.confirmed.toString()}");
            } else if (snapshot.hasError) {
              return Text("${snapshot.error}");
            }

            return CircularProgressIndicator();
          },
        ));

应用程序仍然停留在CircularProgressIndicator上,并且不显示错误。

转载请注明出处:http://www.xjzlzx.com/article/20230519/1140428.html