Home > Back-end >  Is there a way of assigning a future variable to another variable without returning null in dart?
Is there a way of assigning a future variable to another variable without returning null in dart?

Time:05-14

I was trying to pass a data to a variable that returns future but it returns out to be null even though I'm using async and await. what is I'm missing here ?

import 'package:http/http.dart' as http;
import 'dart:convert';

const apiKey = 'deac2cf3c5bb6ee4e7350802f47595bd';
const apiURL =
'https://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=$apiKey';

var lon;
void main() async {
lon = await Weather().longitude;
print(lon); // returns null
}

class Weather {
var longitude;
Weather({this.longitude});

void getWeatherData() async {
Uri parsedUrl = Uri.parse(apiURL);
http.Response response = await http.get(parsedUrl);

if (response.statusCode == 200) {
  longitude = jsonDecode(response.body)['coord']['lon'];
 
      }
   }
}

Expected output : 139 Actual output: null

CodePudding user response:

you are awaiting the constructor, which is not an async function anyway plus you are accessing the variable longtiude which has not been set yet, you need to call the function getWeatherData first

final weather = Weather();
await weather.getWeatherData();
print(weather.longtiude);
  • Related