📜  由于 api 响应延迟导致的 null 错误 - 无论代码示例

📅  最后修改于: 2022-03-11 14:59:42.196000             🧑  作者: Mango

代码示例2
Future fetchDataCity() async {
  // your code
  weatherCity = WeatherCity.fromJson(cityDecodedJson);
  return weatherCity;
}

Future fetchDataWeather() async {
  // your code
  weatherData = WeatherData.fromJson(decodedJson);
  return weatherData;
}

// in your build method
@override
Widget build(BuildContext context) {
  return Scaffold(
    body: Container(
      child: FutureBuilder(
        future: fetchDataWeather(), // a previously-obtained Future or null
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          switch (snapshot.connectionState)
            case ConnectionState.active:
            case ConnectionState.waiting:
              return Text('Awaiting result...'); //or a placeholder
            case ConnectionState.done:
              if (snapshot.hasError){
                return Text('Error: ${snapshot.error}');
              } else {
                return Text('Error: ${snapshot.data}');
            }
         },
      ) //FutureBuilder
    ),
  );
}