【发布时间】:2021-03-05 13:41:07
【问题描述】:
我正在学习将 API 与 Flutter 一起使用,并且我正在尝试使用 Open Weather Map,但是我的代码在我在 URL 中使用的每个变量中插入了 %7B 和 %7D。
实际网址:
https://api.openweathermap.org/data/2.5/weather?lat=%7B-15.783783783783784%7D&lon=%7B-47.93345625648786%7D&appid=%7Bf0060b47028a54500c466c7288e41d31%7D
这就是我想要的:
https://api.openweathermap.org/data/2.5/weather?lat=-15.783783783783784&lon=-47.93345625648786&appid=f0060b47028a54500c466c7288e41d31
我的代码有什么问题?
我的代码:
import 'package:flutter/material.dart';
import 'package:clima/services/location.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
const apiKey = 'f0060b47028a54500c466c7288e41d31';
class LoadingScreen extends StatefulWidget {
@override
_LoadingScreenState createState() => _LoadingScreenState();
}
class _LoadingScreenState extends State<LoadingScreen> {
double latitude;
double longitude;
void getLocation() async {
Location location = Location();
await location.getCurrentLocation();
latitude = location.latitude;
longitude = location.longitude;
getData();
}
void getData() async {
var url = Uri.https('api.openweathermap.org', '/data/2.5/weather', {
'lat': '{$latitude}',
'lon': '{$longitude}',
'appid': '{$apiKey}',
});
var response = await http.get(url);
if (response.statusCode == 200) {
String data = response.body;
var temperature = jsonDecode(data)['main']['temp'];
print(temperature);
} else {
print(response.statusCode);
print(url);
}
}
@override
void initState() {
getLocation();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold();
}
@override
void deactivate() {
super.deactivate();
}
}
【问题讨论】:
标签: flutter dart openweathermap