Flutter天气预报插件open_weather_api_client的使用

发布于 1周前 作者 zlyuanteng 来自 Flutter

Flutter天气预报插件open_weather_api_client的使用

该插件提供了与OpenWeather API端点交互的非官方但全面的Dart库。

特性

  • 🚀 跨平台支持:支持iOS、Android、Mac、Windows、Linux和Web。
  • 💯 支持通过坐标和城市名称查询。
  • 🛡 强大的错误处理系统,支持连接检查、超时、意外错误和多种可能由OpenWeather API端点返回的错误响应。
  • 💪 支持查询OpenWeather端点支持的所有语言。
  • ⚙️ 稳健的单位转换选项,支持将温度、气压、速度、距离和降水量转换为所需的单位。
  • ❤️ 简单的API,直观地映射到OpenWeather端点。
  • ⚡ 经过生产测试(在我的应用中进行测试,您可以在这里查看:这里)。
  • 🔋 包含所有必需的组件。

入门指南

每个单独的OpenWeather端点都有其对应的天气工厂类和数据模型类。请注意,解析出的任何数值数据都会以最高可能的精度返回。

当前天气端点

当前天气端点可以通过CurrentWeatherFactory类查询,并返回一个包含请求状态和CurrentWeather实例的元组(如果请求成功)。

CurrentWeatherFactory factory = CurrentWeatherFactory(
  apiKey: /// 您的API密钥
  language: /// 默认为英语,可用语言在文档中列出
  settings: /// `UnitSettings`的一个实例,包含您希望接收的天气数据单位配置
  locationCoords: /// `LocationCoords`的一个实例,包含您要查询天气的纬度和经度
  cityName: /// 您要查询天气的城市名称
  maxTimeBeforeTimeout: /// 请求超时前的最大等待时间
);

/// 请求天气并等待结果
RequestResponse<CurrentWeather?> result = await factory.getWeather();

if (result.requestStatus == RequestStatus.Successful) {
  /// 请求成功
  print(result.response!.cityName);
} else {
  /// 请求未成功,根据导致失败的错误更新UI
  print(result.requestStatus);
}

OneCall端点

OneCall端点可以通过OneCallWeatherFactory查询,并返回一个包含请求状态和OneCallWeather实例的元组(如果请求成功)。

OneCallWeatherFactory factory = OneCallWeatherFactory(
  apiKey: /// 您的API密钥
  language: /// 默认为英语,可用语言进一步列出
  settings: /// `UnitSettings`的一个实例,包含您希望接收的天气数据单位配置
  locationCoords: /// `LocationCoords`的一个实例,包含您要查询天气的纬度和经度
  exclusions: /// `ExcludeField`类型的数组,对应您要从OneCall端点查询中排除的字段,默认为无
  maxTimeBeforeTimeout: /// 请求超时前的最大等待时间
);

/// 请求天气并等待结果
RequestResponse<OneCallWeather?> result = await factory.getWeather();

if (result.requestStatus == RequestStatus.Successful) {
  /// 请求成功
  print(result.response!.cityName);
} else {
  /// 请求未成功,根据导致失败的错误更新UI
  print(result.requestStatus);
}

如OpenWeather文档所述,OneCall API有一个参数可以排除某些字段(例如当前天气预报或每小时天气预报)从服务器返回的响应。

OneCall端点支持的所有可排除字段都表示在ExcludeField枚举中,而OneCallWeatherFactory类中的exclusions数组字段中包含的字段将从查询中排除。

该类能够解析来自服务器的完整请求响应,但建议仅查询所需字段,这既加速了解析过程,又节省了API密钥的调用次数。

TODOs

  • ✅ 更好的文档
  • ✅ 更好的文档
  • ✅ 减少依赖
  • ❌ 单元测试
  • ❌ 支持Geocoding端点
  • ❌ 支持5天预报端点
  • ❌ 支持空气质量端点
  • ❊ 支持天气地图1.0端点(包括渲染地图的小部件)
  • ❊ 完整支持错误处理,包括边缘情况
  • ✅ 实现更多单位设置

注意事项

此包不支持需要会员资格才能查询的API端点,部分原因是我没有具有所需会员资格的API密钥,部分原因是很少有人使用API的付费部分。

如果您确实拥有与具有所需会员资格的账户关联的API密钥,请发送拉取请求,这将极大地帮助项目。

如果您确实拥有具有所需权限的账户,但没有时间贡献,请联系我,我愿意生成一个API密钥供您使用(仅用于测试高级端点所需的少量调用)。

许可证

该包在Apache许可证2.0下授权。

Copyright 2021 Tanzil Zubair Bin Zaman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

除非适用法律要求或书面同意,否则根据许可证分发的软件按“原样”分发,不附带任何明示或暗示的保证,包括但不限于适销性、特定用途适用性和非侵权性的保证。有关许可证具体管理的许可和限制的语言,请参阅许可证。

示例代码

使用Current Weather API端点的示例

import 'package:flutter/material.dart';
import 'package:open_weather_api_client/open_weather_api_client.dart';

class Example1 extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Column(
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          GestureDetector(
            onTap: () async {
              // 设置天气工厂
              CurrentWeatherFactory factory = CurrentWeatherFactory(
                apiKey: "您的API密钥",
                settings: UnitSettings(
                  windSpeedUnit: WindSpeedUnit.Knots,
                ),
                cityName: "伦敦",
              );

              // 请求天气
              RequestResponse<CurrentWeather?> result = await factory.getWeather();

              // 检查请求是否成功
              if (result.requestStatus == RequestStatus.Successful) {
                // 打印从服务器获取的城市名
                print(result.response!.cityName);
                // 打印温度
                print(result.response!.temp);
                // 打印天气类型
                print(result.response!.weatherType);
              } else {
                // 打印发生的错误
                print("发生错误类型 ${result.requestStatus}");
              }
            },
            child: Container(
              width: 200,
              height: 100,
              alignment: Alignment.center,
              color: Colors.green,
              child: Text(
                "获取伦敦天气",
                style: TextStyle(
                  fontSize: 20.0,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

使用One Call API端点的示例

import 'package:flutter/material.dart';
import 'package:open_weather_api_client/open_weather_api_client.dart';

class Example2 extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Column(
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          GestureDetector(
            onTap: () async {
              // 设置天气工厂
              OneCallWeatherFactory factory = OneCallWeatherFactory(
                apiKey: "您的API密钥",
                settings: UnitSettings(
                  windSpeedUnit: WindSpeedUnit.Knots,
                ),
                locationCoords: LocationCoords(
                  longitude: 51.5074,
                  latitude: 0.1278,
                ),
                maxTimeBeforeTimeout: Duration(seconds: 10),
              );

              // 请求天气
              RequestResponse<OneCallWeather?> result = await factory.getWeather();

              // 检查请求是否成功
              if (result.requestStatus == RequestStatus.Successful) {
                // 打印当前天气类型
                print(result.response!.currentWeather!.weatherType);
                // 打印下一小时的天气类型
                print(result.response!.hourlyWeather![1]!.weatherType);
                // 打印30分钟后降水金额
                print(result.response!.minutelyWeather![29]!.precipitationAmount);
              } else {
                // 打印发生的错误
                print("发生错误类型 ${result.requestStatus}");
              }
            },
            child: Container(
              width: 200,
              height: 100,
              alignment: Alignment.center,
              color: Colors.green,
              child: Text(
                "获取伦敦天气",
                style: TextStyle(
                  fontSize: 20.0,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

更多关于Flutter天气预报插件open_weather_api_client的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter天气预报插件open_weather_api_client的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何使用 open_weather_api_client 插件在 Flutter 中实现天气预报功能的代码示例。这个示例将展示如何获取当前城市的天气数据,并在界面上显示。

首先,确保你已经在你的 pubspec.yaml 文件中添加了 open_weather_api_client 依赖:

dependencies:
  flutter:
    sdk: flutter
  open_weather_api_client: ^x.y.z  # 替换为最新版本号

然后,运行 flutter pub get 来获取依赖。

接下来,我们将编写一个简单的 Flutter 应用,使用 open_weather_api_client 插件来获取并显示天气数据。

1. 创建一个新的 Flutter 项目

如果还没有项目,可以使用以下命令创建一个新的 Flutter 项目:

flutter create weather_app
cd weather_app

2. 配置 API Key

为了使用 OpenWeatherMap API,你需要一个 API Key。你可以在 OpenWeatherMap 网站上注册并获取一个免费的 API Key。然后,将这个 Key 存储在项目的某个安全位置,例如 .env 文件(你需要安装 flutter_dotenv 插件来读取这个文件)或者直接在代码中(不推荐这样做,因为它不安全)。

3. 编写代码

main.dart

import 'package:flutter/material.dart';
import 'package:open_weather_api_client/open_weather_api_client.dart';
import 'dart:async';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Weather App',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: WeatherHome(),
    );
  }
}

class WeatherHome extends StatefulWidget {
  @override
  _WeatherHomeState createState() => _WeatherHomeState();
}

class _WeatherHomeState extends State<WeatherHome> {
  String cityName = 'London';
  String weatherDescription = '';
  double temperature = 0.0;
  bool isLoading = true;

  @override
  void initState() {
    super.initState();
    _getWeatherData();
  }

  Future<void> _getWeatherData() async {
    String apiKey = 'YOUR_API_KEY';  // 替换为你的 OpenWeatherMap API Key
    final client = OpenWeatherApiClient(apiKey: apiKey);

    try {
      final response = await client.getCurrentWeatherByCityName(cityName);
      setState(() {
        weatherDescription = response.weather[0].description;
        temperature = response.main.temp - 273.15; // 将 Kelvin 转换为 Celsius
        isLoading = false;
      });
    } catch (e) {
      print(e);
      setState(() {
        isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Weather App'),
      ),
      body: Center(
        child: isLoading
            ? CircularProgressIndicator()
            : Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    'Weather in $cityName:',
                    style: TextStyle(fontSize: 24),
                  ),
                  SizedBox(height: 10),
                  Text(
                    weatherDescription,
                    style: TextStyle(fontSize: 18, color: Colors.grey),
                  ),
                  SizedBox(height: 10),
                  Text(
                    '${temperature.toStringAsFixed(1)}°C',
                    style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
                  ),
                ],
              ),
      ),
    );
  }
}

4. 运行应用

使用以下命令运行你的 Flutter 应用:

flutter run

这个示例展示了如何使用 open_weather_api_client 插件获取当前城市的天气数据,并在 Flutter 应用中显示。你可以根据需要进一步扩展这个示例,例如添加更多的城市选择、显示更多的天气信息、处理错误等。

回到顶部