【问题标题】:API Key not working in Flutter Weather API App (Android)API 密钥在 Flutter Weather API 应用程序(Android)中不起作用
【发布时间】:2023-03-09 01:39:01
【问题描述】:

我正在学习 Flutter 并尝试构建一个 Android 应用程序。基本上是一个天气应用程序,它从站点获取 API 密钥。我不断收到错误“无法将参数类型'String'分配给参数类型'Uri'。”。这甚至意味着什么?我该如何让它发挥作用?

main.dart

import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

void main() => runApp(
  MaterialApp(
    title: "Weather App",
    home: Home(),
  )
);

class Home extends StatefulWidget {
  @override
  State<StatefulWidget> createState(){
    return _HomeState();
  }
}

class _HomeState extends State<Home> {

  var temp;
  var description;
  var currently;
  var humidity;
  var windSpeed;

  Future getWeather () async {
    http.Response response = await http.get("http://api.weatherapi.com/v1/current.json?key=e5bd00e528e346ff8a840254213009&q=Chatham Ontario&aqi=no");
    var results = jsonDecode(response.body);
    setState((){
      this.temp = results['current']['temp_c'];
      this.description = results['current'][0]['last_updated'];
      this.currently = results['current'][0]['condition']['text'];
      this.humidity = results['current']['humidity'];
      this.windSpeed = results['current']['wind_kph'];
    });
  }

  @override
  void initState() {
    super.initState();
    this.getWeather();
  }

  @override
  Widget build (BuildContext context) {
    return Scaffold(
      body: Column(
        children: <Widget>[
          Container(
            height: MediaQuery.of(context).size.height / 3,
            width: MediaQuery.of(context).size.width,
            color: Colors.red,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Padding(
                  padding:EdgeInsets.only(bottom: 10.0),
                  child: Text(
                    "Currently in Chatham-Kent",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 14.0,
                      fontWeight: FontWeight.w600
                    ),
                  ),
                ),
                Text(
                  temp != null ? temp.toString() + "\u00B0" : "Loading",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 40.0,
                    fontWeight: FontWeight.w600
                  ),
                ),
                Padding(
                  padding:EdgeInsets.only(top: 10.0),
                  child: Text(
                    currently != null ? currently.toString() : "Loading",
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 14.0,
                        fontWeight: FontWeight.w600
                    ),
                  ),
                ),
              ],
            ),
          ),
          Expanded(
            child: Padding(
              padding: EdgeInsets.all(20.0),
              child: ListView(
                children: <Widget>[
                  ListTile(
                    leading: FaIcon(FontAwesomeIcons.thermometerHalf),
                    title: Text("Temperature"),
                    trailing: Text(temp != null ? temp.toString() + "\u00B0" : "Loading"),
                  ),
                  ListTile(
                    leading: FaIcon(FontAwesomeIcons.cloud),
                    title: Text("Weather"),
                    trailing: Text(description != null ? description.toString() : "Loading"),
                  ),
                  ListTile(
                    leading: FaIcon(FontAwesomeIcons.sun),
                    title: Text("Humidity"),
                    trailing: Text(humidity != null ? humidity.toString() : "Loading"),
                  ),
                  ListTile(
                    leading: FaIcon(FontAwesomeIcons.wind),
                    title: Text("Wind Speed"),
                    trailing: Text(windSpeed != null ? windSpeed.toString() : "Loading"),
                  )
                ],
              )
            )
          )
        ],
      ),
    );
  }
}

pubspec.yaml

version: 1.0.0+1

environment:
  sdk: '>=2.10.0 <3.0.0'

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.2
  font_awesome_flutter: ^8.0.0
  http: ^0.13.3

dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_lints: ^1.0.0

flutter:
  uses-material-design: true

【问题讨论】:

    标签: json flutter api weather


    【解决方案1】:

    嗯,你的错误很明显是The argument type 'String' can't be assigned to the parameter type 'Uri',所以你必须将url字符串转换为Uri

    像这样:

    var uri = Uri.parse("http://api.weatherapi.com/v1/current.json?key=e5bd00e528e346ff8a840254213009&q=Chatham Ontario&aqi=no");
     http.Response response = await http.get(uri);
    
    

    【讨论】:

      【解决方案2】:

      更改这行代码

      http.Response response = await http.get("http://api.weatherapi.com/v1/current.json?key=e5bd00e528e346ff8a840254213009&q=Chatham Ontario&aqi=no");
      

      http.Response response = await http.get(Uri.parse("http://api.weatherapi.com/v1/current.json?key=e5bd00e528e346ff8a840254213009&q=Chatham Ontario&aqi=no"));
      

      【讨论】:

        【解决方案3】:

        基于HTTP package docs here.

        从 0.13.0-nullsafety.0 版本开始 以前允许传递 String 或 Uri 的所有 API 现在都需要 Uri。 所以这里发生的事情是您需要在调用之前先将您的字符串解析(转换)为uri。

        所以你的天气函数会是这样的:

        Future getWeather () async {
        http.Response response = await http.get(Uri.parse("http://api.weatherapi.com/v1/current.json?key=e5bd00e528e346ff8a840254213009&q=Chatham Ontario&aqi=no"));
        var results = jsonDecode(response.body);
        setState((){
          this.temp = results['current']['temp_c'];
          this.description = results['current'][0]['last_updated'];
          this.currently = results['current'][0]['condition']['text'];
          this.humidity = results['current']['humidity'];
          this.windSpeed = results['current']['wind_kph'];
        });
        }
        

        【讨论】:

          猜你喜欢
          • 2015-03-23
          • 2021-11-25
          • 2020-10-23
          • 1970-01-01
          • 2018-02-21
          • 1970-01-01
          • 2016-11-12
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多