URL 因为 %love 处于 %limit

URL with %7B and %7D

我正在学习将 API 与 Flutter 结合使用,我正在尝试为此使用开放天气图,但是,我的代码在我在 URL.

实际 URL:

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();
  }
}

在您的 getData() 函数中,尝试删除 url 参数周围的 curly 大括号,如下所示:

var url = Uri.https('api.openweathermap.org', '/data/2.5/weather', {
  'lat': '$latitude',
  'lon': '$longitude',
  'appid': '$apiKey',
});

或者,您可以像这样自己连接 URL 字符串。

var baseUrl = 'https://api.openweathermap.org/data/2.5/weather?';
var appid = 'f0060b47028a54500c466c7288e41d31';
var latString = '-15.783783783783784';
var lonString = '-47.93345625648786';

var urlString =
    baseUrl + 'lat=$latString' + '&' + 'lon=$lonString' + '&' + 'appid=$appid';