flutter实现天气预报
时间: 2023-08-16 20:04:45 浏览: 57
Flutter 是一个跨平台的移动应用开发框架,可以使用 Dart 语言进行开发。要实现天气预报功能,你可以按照以下步骤进行操作:
1. 导入相关依赖:在 pubspec.yaml 文件中添加 http 和 json_serializable 依赖。http 用于发送网络请求,json_serializable 用于序列化和反序列化 JSON 数据。
```yaml
dependencies:
flutter:
sdk: flutter
http: ^0.13.3
json_serializable: ^4.4.0
```
2. 创建数据模型:根据天气 API 返回的 JSON 数据,创建相应的数据模型。例如,可以创建 Weather 类来表示天气信息。
```dart
import 'package:json_annotation/json_annotation.dart';
part 'weather.g.dart';
@JsonSerializable()
class Weather {
final String city;
final double temperature;
final String description;
Weather({required this.city, required this.temperature, required this.description});
factory Weather.fromJson(Map<String, dynamic> json) => _$WeatherFromJson(json);
Map<String, dynamic> toJson() => _$WeatherToJson(this);
}
```
3. 生成序列化代码:运行以下命令生成序列化代码:
```bash
flutter pub run build_runner build
```
4. 创建网络请求服务:可以创建一个 WeatherService 类,封装获取天气数据的网络请求。
```dart
import 'package:http/http.dart' as http;
class WeatherService {
static const String apiKey = 'YOUR_API_KEY';
static Future<Weather> fetchWeather(String city) async {
final url = Uri.parse('https://api.weatherapi.com/v1/current.json?key=$apiKey&q=$city');
final response = await http.get(url);
if (response.statusCode == 200) {
final json = jsonDecode(response.body);
return Weather.fromJson(json['current']);
} else {
throw Exception('Failed to fetch weather');
}
}
}
```
5. 创建天气预报界面:使用 Flutter 的 Widget 构建界面,可以显示天气信息。
```dart
import 'package:flutter/material.dart';
class WeatherPage extends StatefulWidget {
final String city;
const WeatherPage({required this.city});
@override
_WeatherPageState createState() => _WeatherPageState();
}
class _WeatherPageState extends State<WeatherPage> {
Weather? _weather;
@override
void initState() {
super.initState();
_fetchWeather();
}
void _fetchWeather() async {
try {
final weather = await WeatherService.fetchWeather(widget.city);
setState(() {
_weather = weather;
});
} catch (e) {
print('Failed to fetch weather: $e');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Weather Forecast'),
),
body: Center(
child: _weather != null
? Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('City: ${_weather!.city}'),
Text('Temperature: ${_weather!.temperature}'),
Text('Description: ${_weather!.description}'),
],
)
: CircularProgressIndicator(),
),
);
}
}
```
以上是一个简单的示例,通过 WeatherService 类发送网络请求获取天气数据,并在 WeatherPage 中显示天气信息。你需要替换 apiKey 为你自己的天气 API 密钥,并根据具体的天气 API 接口文档进行调整。希望对你有所帮助!