WeatherPack 是一個 Flutter/Dart 套件,可簡化從 OpenWeatherMap API 取得天氣資料的過程。它支援地理編碼以取得基於位置的預報,並提供彈性的單位測量(公制、英制、開爾文)。此套件專為跨平台使用設計,可在 Android、iOS、Web、macOS、Windows 與 Linux 上順暢運作。該套件抽象了 API 的複雜性,為開發者提供乾淨且易用的方法,以便將即時天氣資訊整合至應用程式中。
適用情境
通過位置取得目前天氣
將天氣預報整合到行動應用程式中
顯示帶有自定義單位的天氣
建構旅行或戶外活動應用
新增位置感知天氣功能
建立天氣儀表板
主要特色
地理編碼支援
多個單元選項
跨平台相容性
簡單 API 結合
即時天氣數據
OpenWeatherMap API 後端
適合對象
行動應用開發者
Web應用程式創建者
物聯網天氣設備
旅行和生活方式應用
天氣儀表板專案
使用建議
需要 OpenWeatherMap API 金鑰
依賴網路連接
僅限OpenWeatherMap服務
可能需要處理速率限制
初始設定需要API配置
不適用於離線天氣存取
原始 README
以下為關聯原始碼儲存庫的 README 原文快照,最新內容請造訪原始碼儲存庫。
weather_pack
A quick way to get access to weather conditions 🌦.
Put a on Pub and favorite ⭐ on Github to keep up with changes and not miss new releases!
Why choose this library?
basic:
🚲 Easy to use - you only need the APIKEY.
🏝 Built-in geocoding - search for locations by assumed names or by coordinates.
🩺 Various units of measurement - speed, temperature, pressure and cardinal points.
🌤 There are original weather icons.
advanced: (Click to open)
🔮 At least one release application is already based on this package. Therefore, there is an
additional guarantee of security and timely updates of this package.
🔓 There is a method for checking your api for correctness.
🧱 It is very easy to customize data models. Create your own data models and take only what
you need from the built-in ones.
🧾 The code is well documented and each class is labeled and decoded. There are unit tests
for the main functions of the package.
🦺 Safe unpacking of types. If the server stops outputting values - your weather model
will have a null field and the application will not crash.
🔧 This package has no unnecessary dependencies and contains minimal code.
Also, all platforms are supported.
*Additionally, pull package locally to examine example folder:
flutter pub unpack
weather_in_console - Dart console application
create_code_for_readme - all examples from current manual
example - easy use
Getting Started
The easiest way to get the current weather:
Future<void> main() async {
const api = 'YOUR_APIKEY'; // TODO: change to your openweathermap APIkeyfinal wService = WeatherService(api);
// get the current weather in AmsterdamfinalWeatherCurrent currently = await wService.currentWeatherByLocation(
latitude: 52.374, longitude: 4.88969);
print(currently);
}
You can also change the request language:
final lang = WeatherLanguage.arabic;
final wService = WeatherService(api, language: lang);
You can use the lang parameter to get the output in your language.
Translation is applied for the city name and description fields.
Usage weather service
Now there are two weather models - WeatherCurrent and WeatherOneCall.
WeatherOneCall includes:
WeatherCurrent
List<WeatherHourly>
List<WeatherMinutely>
List<WeatherDaily>
List<WeatherAlert>
How to use?
You can get the weather in the following way:
Future<void> getOnecallWeatherWays({String api = 'Your_APIkey'}) async {
final wService2_5 = WeatherService(api, oneCallApi: OneCallApi.api_2_5);
finalWeatherOneCall onecall2_5 = await wService2_5.oneCallWeatherByLocation(
latitude: 52.374, longitude: 4.88969);
print(onecall2_5);
// if you use the "One Call API 3.0" subscription that...final wService3_0 = WeatherService(api, oneCallApi: OneCallApi.api_3_0);
finalWeatherOneCall onecall3_0 = await wService3_0.oneCallWeatherByLocation(
latitude: 52.374, longitude: 4.88969);
print(onecall3_0);
}
Why do you only use the weather search by coordinates?
According to the website OWM:
Please use Geocoder API if you need automatic convert city names and zip-codes to geo
coordinates and the other way around.
Please note that built-in geocoder has been deprecated. Although it is still available for use,
bug fixing and updates are no longer available for this functionality.
Usage geocoding service
GeocodingService is a service for easy location search when working with geographical names
and coordinates. Supports both the direct and reverse methods:
Direct geocoding converts the specified name of a location or zip/post code into
the exact geographical coordinates;
Reverse geocoding converts the geographical coordinates into the names of the nearby locations;
To find using country code and zip code use zip geocoding:
finalPlaceGeocode place = await gService.getLocationByZipAndCountryCode(
zipCode: 'E14',
countryCode: 'GB',
);
Usage units measure
By default, all weather models, e.g. WeatherCurrent, have measurable values of type double.
To display the data in a convenient format, it is necessary use the conversion method value
or valueToString:
voidworksTempUnits({
double temp = 270.78, // ex. received from [WeatherCurrent.temp]int precision = 3,
Temp unitsMeasure = Temp.celsius,
}) {
// The default temperature is measured in Kelvin of the `double` type.// We need the temperature to be displayed in Celsius to 3 decimal placesprint(unitsMeasure.value(temp, precision)); // `-2.37` type `double`print(unitsMeasure.valueToString(temp, precision)); // `-2.370` type `String`// if precision is 0:print(unitsMeasure.value(temp, 0)); // `-2.0` type `double`print(unitsMeasure.valueToString(temp, 0)); // `-2` type `String`
}
By and large, the valueToString() method is needed to display correctly in ui,
and the value() method is for accurate calculations.
There are several units of measurement:
Units of measure
Class
Supported units
Conversion
Temperature
Temp
kelvin, celsius, fahrenheit
+
Speed
Speed
ms, mph, kph
+
Pressure
Pressure
hectoPa, mbar, mmHg, kPa, atm, inHg
+
Cardinal points
SideOfTheWorld
n, ne, e, se, s, sw, w, nw
+(another)
💡 Tip: The SideOfTheWorld enum contains a static method fromDegrees() for converting degrees
to cardinal directions.
Exception handling
Each of the methods in the WeatherService and GeocodingService services can throw an OwmApiException exception. You can process them as follows:
For GeocodingService and WeatherService you can create a custom OWMBuilder for debugging and logging cases:
classOWMBuilderCustomextendsOWMBuilder{
/// We output the url to the console for debugging and logging@overrideFuture<T> getData<T>(
{requiredUri uri, required T Function(dynamic data) builder}) {
print(uri);
returnsuper.getData(uri: uri, builder: builder);
}
}
voidworkOwmBuilder({
String api = 'your_apikey',
}) async {
final customOWMBuilder = OWMBuilderCustom();
final gService = GeocodingService(api, owmBuilder: customOWMBuilder);
finalList<PlaceGeocode> places = await gService.getLocationByCoordinates(
latitude: 52.374, longitude: 4.88969);
print(places);
}
For OWMTestService you can create a custom Client. A more low-level way, would require an explicit dependency on the http package:
classCustomClientextendsIOClient{
/// We output the url to the console@overrideFuture<Response> get(Uri url, {Map<String, String>? headers}) {
print(url);
returnsuper.get(url, headers: headers);
}
}
/// We output the url to the console for debuggingvoidworkCustomClient({
String api = 'your_apikey',
}) async {
final customClient = CustomClient();
final testService = OWMTestService(api, customClient);
finalbool isValidKey = await testService.isValidApikey();
print(isValidKey);
}
Usage weather icons
You can use weather icons provided by the OWM service. See more about weather conditions.
Icons are stored locally in this package at the path assets/weather_icons/.
They are ordered according to Declaring resolution-aware image assets.
This reflects the following correspondences:
WidgetgetWeatherIcon(WeatherCurrent weather) {
returnImage.asset(
'assets/weather_icons/${weather.weatherIcon}.png', // icon path
package: 'weather_pack', // name package
filterQuality: FilterQuality.high, // optional
errorBuilder: (c, e, s) => Text(e), // will return the widget in case of an error
);
}
In this case, you can use the best quality regardless of platform resolution by specifying @4 to path:
'assets/weather_icons/@4/$weatherIcon.png'
API key testing
It is possible to test the API key.
To do this, the OWMTestService class has a method isValidApikeyForOneCall:
/// If the apikey is valid, `OWMApiTest` methods will return `true`Future<void> testAPIkey({
String testedAPIkey = 'your_apikey',
}) async {
// checking key for geocoding service and for (fetching WeatherCurrent)finalbool isValid = awaitOWMTestService(testedAPIkey).isValidApikey();
// checking key for "One Call API 2.5" service (fetching WeatherOneCall)finalbool isValidOneCall2 = awaitOWMTestService(testedAPIkey)
.isValidApikeyForOneCall(OneCallApi.api_2_5);
// or// checking key for "One Call by Call 3.0" service (fetching WeatherOneCall)finalbool isValidOneCall3 = awaitOWMTestService(testedAPIkey)
.isValidApikeyForOneCall(OneCallApi.api_3_0);
}
Resources
folder example.
There is a simple example of how to use the basic functions of the package, as well as a console mini-application without using flutter