【问题标题】:URL with %7B and %7D带有 %7B 和 %7D 的 URL
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2022-06-14
      • 1970-01-01
      • 2014-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-10
      • 2016-12-18
      相关资源
      最近更新 更多