有没有办法在不返回 null 的情况下将未来变量分配给另一个变量?

Is there a way of assigning a future variable to another variable without returning null in dart?

我试图将数据传递给 returns 未来的变量,但它 returns 结果为空,即使我正在使用异步和等待。我在这里缺少什么?

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'];
 
      }
   }
}

预期输出: 139 实际输出: 空

你正在等待构造函数,它不是异步函数,而且你正在访问尚未设置的变量 longtiude,你需要先调用函数 getWeatherData

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