Flutter天气数据获取插件weather_open_meteo_client的使用
Flutter天气数据获取插件weather_open_meteo_client的使用
该插件使用OpenMeteo API 获取当前天气状态以及天气预报。
天气可以通过提供地理坐标或城市名称来获取。
安装(Flutter)
在 pubspec.yaml
文件中添加 weather_open_meteo_client
作为依赖项。
有关如何添加依赖项的帮助,请参阅 pubspec 文档。
dependencies:
weather_open_meteo_client: ^x.x.x
使用
通过城市名称
import 'package:weather_open_meteo_client/weather_open_meteo_client.dart';
void fetchWeatherByCityName() async {
OpenMeteoApi _weather = OpenMeteoApi();
Weather tempWether = await _weather.getWeatherByCityName('London');
print(tempWether.current_weather!.temperature);
}
通过坐标
import 'package:weather_open_meteo_client/weather_open_meteo_client.dart';
void fetchWeatherByCoordinate() async {
OpenMeteoApi _weather = OpenMeteoApi();
Weather tempWether = await _weather.getWeatherByCoordinate(latitude: 51.5072, longitude: -0.1275, current_weather: true);
print(tempWether.current_weather!.temperature);
}
当前天气
对于当前天气 API 的具体文档,请参见 API 文档。
示例代码
以下是完整的示例代码:
import 'package:flutter/material.dart';
import 'package:weather_open_meteo_client/weather_open_meteo_client.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
[@override](/user/override)
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
double _counter = 0.0;
void _incrementCounter() async {
OpenMeteoApi _weather = OpenMeteoApi();
Weather tempWether = await _weather.getWeatherByCityName('London');
if (tempWether.current_weather != null) {
_counter = tempWether.current_weather!.temperature!;
}
setState(() {});
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'TEMP OF LONDON',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'get_temperature',
child: const Icon(Icons.add),
),
);
}
}
更多关于Flutter天气数据获取插件weather_open_meteo_client的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter天气数据获取插件weather_open_meteo_client的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个使用 weather_open_meteo_client
插件来获取天气数据的 Flutter 代码示例。这个插件允许你通过 OpenMeteo API 获取实时的天气信息。
首先,确保你已经在 pubspec.yaml
文件中添加了 weather_open_meteo_client
依赖:
dependencies:
flutter:
sdk: flutter
weather_open_meteo_client: ^最新版本号 # 请替换为最新版本号
然后,运行 flutter pub get
来安装依赖。
以下是一个完整的 Flutter 应用示例,展示了如何使用 weather_open_meteo_client
获取天气数据:
import 'package:flutter/material.dart';
import 'package:weather_open_meteo_client/weather_open_meteo_client.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Weather App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: WeatherScreen(),
);
}
}
class WeatherScreen extends StatefulWidget {
@override
_WeatherScreenState createState() => _WeatherScreenState();
}
class _WeatherScreenState extends State<WeatherScreen> {
late OpenMeteoClient _client;
late Future<CurrentWeather?> _futureWeather;
@override
void initState() {
super.initState();
String apiKey = 'YOUR_API_KEY'; // 请替换为你的 OpenMeteo API Key
_client = OpenMeteoClient(apiKey: apiKey);
_futureWeather = _fetchWeather('London'); // 替换为你想查询的城市
}
Future<CurrentWeather?> _fetchWeather(String location) async {
try {
final weatherResponse = await _client.getCurrentWeatherByLocation(location);
return weatherResponse;
} catch (e) {
print('Error fetching weather: $e');
return null;
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Weather App'),
),
body: Center(
child: FutureBuilder<CurrentWeather?>(
future: _futureWeather,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else if (snapshot.data == null) {
return Text('No weather data.');
} else {
CurrentWeather weather = snapshot.data!;
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Temperature: ${weather.temperature.value}°C',
style: TextStyle(fontSize: 24),
),
SizedBox(height: 10),
Text(
'Weather: ${weather.weatherDescription}',
style: TextStyle(fontSize: 18),
),
],
);
}
},
),
),
);
}
}
代码说明:
- 依赖添加:在
pubspec.yaml
中添加weather_open_meteo_client
依赖。 - API Key:在
initState
方法中初始化OpenMeteoClient
,并传入你的 OpenMeteo API Key。 - 数据获取:使用
_fetchWeather
方法通过城市名称获取天气数据。 - UI 显示:使用
FutureBuilder
来异步加载天气数据,并在加载完成后显示温度和天气描述。
请确保你已经注册了 OpenMeteo API 并获得了有效的 API Key。此外,你可能需要根据实际返回的数据结构对 UI 显示部分进行调整。