天气应用:未来三天
本课属于 Coddy Flutter 学习旅程的“数据与网络”单元。第 24 课,共 27 课。
城市对应的答案还包含天气预报:对象中的一个 JSON 列表,每天一项。
"forecast": [
{"date": "2026-10-20", "condition": "Cloudy", "high": 22, "low": 15},
...
]读取对象中的列表和单独读取列表的方式相同:先将它取出为 as List<dynamic>,然后用各自的 fromJson 处理每一项。看看文件底部的 Weather.fromJson:它已经完成了这些操作,所以 weather.forecast 是一个 List<DayForecast>。
final days = json['forecast'] as List<dynamic>;
forecast: days
.map((day) => DayForecast.fromJson(day as Map<String, dynamic>))
.toList(),每天都有一个 DateTime。DateFormat('EEEE') 会将它转换为星期几的全称,例如“星期二”。在 Column 的 children 中使用 for,可以为每天创建一行。
挑战
中等在当前天气下方,显示接下来的 3 天:
- 导入
package:intl/intl.dart - 在
SizedBox(height: 32)后,为每天添加一个Row:在Expanded中显示星期几,使用DateFormat('EEEE'),然后显示最高温度和最低温度,例如22° / 15° - 为每一行的左右两侧各添加
32像素的内边距
亲手试试
import 'dart:convert';
import 'package:flutter/material.dart';
import 'api.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: WeatherScreen(),
);
}
}
class WeatherScreen extends StatefulWidget {
const WeatherScreen({super.key});
@override
State<WeatherScreen> createState() => _WeatherScreenState();
}
class _WeatherScreenState extends State<WeatherScreen> {
late Future<Weather> _weather;
@override
void initState() {
super.initState();
_weather = loadWeather();
}
Future<Weather> loadWeather() async {
final body = await fetch('/weather/lisbon');
return Weather.fromJson(jsonDecode(body));
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Weather')),
body: Center(
child: FutureBuilder<Weather>(
future: _weather,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text('Could not load: ${snapshot.error}');
}
if (snapshot.hasData) {
return buildWeather(snapshot.data!);
}
return const CircularProgressIndicator();
},
),
),
);
}
Widget buildWeather(Weather weather) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(weather.city, style: const TextStyle(fontSize: 32)),
Text(
'${weather.temperature}°',
style: const TextStyle(fontSize: 72, fontWeight: FontWeight.bold),
),
Text(weather.condition, style: const TextStyle(fontSize: 24)),
],
);
}
}
class Weather {
Weather({
required this.city,
required this.temperature,
required this.condition,
required this.forecast,
});
final String city;
final int temperature;
final String condition;
final List<DayForecast> forecast;
factory Weather.fromJson(Map<String, dynamic> json) {
final days = json['forecast'] as List<dynamic>;
return Weather(
city: json['city'] as String,
temperature: json['temperature'] as int,
condition: json['condition'] as String,
forecast: days
.map((day) => DayForecast.fromJson(day as Map<String, dynamic>))
.toList(),
);
}
}
class DayForecast {
DayForecast({
required this.date,
required this.condition,
required this.high,
required this.low,
});
final DateTime date;
final String condition;
final int high;
final int low;
factory DayForecast.fromJson(Map<String, dynamic> json) {
return DayForecast(
date: DateTime.parse(json['date'] as String),
condition: json['condition'] as String,
high: json['high'] as int,
low: json['low'] as int,
);
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
数据与网络中的所有课
自己练习: Flutter 在线编译器