null error due to delay in api response code example

Example 1: null error due to delay in api response

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

Widget build(BuildContext context) {
  return Scaffold(
    body: Container(
      child: FutureBuilder(
        future: fetchDataWeather(), // a previously-obtained Future or null
        builder: (BuildContext context, AsyncSnapshot<String> 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
    ),
  );
}

Example 2: null error due to delay in api response

String text;

fetchData() async {
//...
  text = weatherData.weather[0].main ?? 'Waiting api response...';
//...
}

// in your build method

Widget build(BuildContext context) {
  return Scaffold(
    body: Container(
      child: Text(text), //this will render "Waiting api response" first, and when the api result arrive, it will change
    ),
  );
}

Tags:

Dart Example