以下は私のコードです:
const apiKey = 'XXXXXXXXXXXXXXXXXXXXXXXXXX';
class LoadingScreen extends StatefulWidget {
@override
_LoadingScreenState createState() => _LoadingScreenState();
}
class _LoadingScreenState extends State<LoadingScreen> {
double latitude;
double longitude;
@override
void initState() {
super.initState();
getLocation();
print('code started');
getData();
}
void getLocation() async {
Location location = Location();
await location.getCurrenctLocation();
print(location.latitude);
print(location.longitude);
latitude = location.latitude; // SAVING LATITUDE POSITION HERE
longitude = location.longitude; // SAVING LONGITUDE POSITION HERE
}
void getData() async {
http.Response response = await http.get(
'https://api.openweathermap.org/data/2.5/weather?lat=25&lon=85&appid=$apiKey');
if (response.statusCode == 200) {
String data = response.body;
var decodedData = jsonDecode(data);
double temperature = decodedData['main']['temp'];
int condition = decodedData['weather'][0]['id'];
String cityName = decodedData['name'];
print(temperature);
print(cityName);
print(condition);
} else {
print(response.statusCode);
}
}
@override
Widget build(BuildContext context) {
return Scaffold();
}
}
今、私はこの出力を得ています:
flutter: code started
flutter: 25.5
flutter: 85.1
flutter: 300.15
flutter: Tekāri
URLを変更すると問題が発生する
変更前: https://api.openweathermap.org/data/2.5/weather?lat=25&lon=85&appid=$apiKey
変更後: https://api.openweathermap.org/data/2.5/weather?lat=$latitude&lon=$longitude&appid=$apiKey
この変更を行った後の出力は次のとおりです。
flutter: code started
flutter: 25.5
flutter: 85.1
flutter: 400
つまり、statusCodeは400であり、エラーが発生しています。しかし、URLの変更を行う前に、私position.latitude
とposition.longitude
しは、変数にこれらの二つのURLを渡し保存私がやった唯一の事だった後のことを、プリントを取得します。statusCodeが400になる理由がわかりません。
このエラーは文字列の補間ではなく、変数の初期化と関係があると思います。
コードを見ると、関数 'getData()'が呼び出されたときに、変数の緯度と経度が初期化されているとは思いません。
'getLocation()'関数内から関数 'getData()'を呼び出し、 'initState()'から削除する必要があります。このような:
void getLocation() async {
Location location = Location();
await location.getCurrenctLocation();
print(location.latitude);
print(location.longitude);
latitude = location.latitude; // SAVING LATITUDE POSITION HERE
longitude = location.longitude; // SAVING LONGITUDE POSITION HERE
getData();
}
それがうまくいくかどうか私に知らせてください!
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加