Flutter天气应用 #
一、项目概述 #
天气应用学习网络请求、JSON解析和异步编程。
二、核心代码 #
2.1 数据模型 #
dart
class Weather {
final String city;
final double temperature;
final String description;
final String icon;
Weather({
required this.city,
required this.temperature,
required this.description,
required this.icon,
});
factory Weather.fromJson(Map<String, dynamic> json) => Weather(
city: json['name'],
temperature: json['main']['temp'].toDouble(),
description: json['weather'][0]['description'],
icon: json['weather'][0]['icon'],
);
}
2.2 网络请求 #
dart
class WeatherService {
final Dio _dio = Dio();
final String apiKey = 'your_api_key';
Future<Weather> getWeather(String city) async {
try {
final response = await _dio.get(
'https://api.openweathermap.org/data/2.5/weather',
queryParameters: {
'q': city,
'appid': apiKey,
'units': 'metric',
},
);
return Weather.fromJson(response.data);
} catch (e) {
throw Exception('Failed to load weather');
}
}
}
三、总结 #
天气应用展示了网络请求和JSON解析。
3.1 下一步 #
让我们学习 电商应用!
最后更新:2026-03-28