App meteo: riprova
Fa parte della sezione Dati e rete del percorso Flutter di Coddy. Lezione 26 di 27.
Le app meteo vengono aperte sui treni, nelle gallerie e in montagna. Senza segnale, l’app dovrebbe dirlo chiaramente e offrire un modo per tornare indietro, non mostrare un indicatore di caricamento che non finisce mai o una riga di testo d’errore.
Dedica all’errore una schermata tutta sua: un’icona, una frase comprensibile, i dettagli sotto e un pulsante Riprova che crea un nuovo future in setState. Inseriscila in un metodo tutto suo, buildError, accanto a buildWeather, così build rimane breve.
if (snapshot.connectionState == ConnectionState.waiting) {
return const CircularProgressIndicator();
}
if (snapshot.hasError) {
return buildError(snapshot.error!);
}
return buildWeather(snapshot.data!);Controllare prima ConnectionState.waiting mostra l’indicatore di caricamento durante ogni caricamento, incluso il secondo tentativo. Quando il future è completato, c’è un errore oppure ci sono dati, quindi l’ultima riga può usare snapshot.data!.
Per vederlo nell’anteprima, scrivi offline = true; come prima riga di main e premi Run. Rimuovilo prima di premere Check.
Sfida
MedioAggiungi una schermata di errore all'app:
- un metodo
buildError(Object error):Icons.cloud_off(dimensione 64),Could not load the weather(dimensione 20), il testo dell'errore e un pulsante Riprova - un metodo
tryAgainche imposta un nuovoloadWeather()insetState - nel builder, controlla prima
ConnectionState.waiting, poi l'errore e infine mostra le condizioni meteo
Provalo tu
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:intl/intl.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));
}
IconData iconFor(String condition) {
return switch (condition) {
'Sunny' => Icons.wb_sunny,
'Cloudy' => Icons.cloud,
'Rainy' => Icons.umbrella,
'Snowy' => Icons.ac_unit,
_ => Icons.help_outline,
};
}
@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)),
Icon(iconFor(weather.condition), size: 96, color: Colors.orange),
Text(
'${weather.temperature}°',
style: const TextStyle(fontSize: 72, fontWeight: FontWeight.bold),
),
Text(weather.condition, style: const TextStyle(fontSize: 24)),
const SizedBox(height: 32),
for (final day in weather.forecast)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 8),
child: Row(
children: [
Icon(iconFor(day.condition)),
const SizedBox(width: 16),
Expanded(
child: Text(
DateFormat('EEEE').format(day.date),
style: const TextStyle(fontSize: 18),
),
),
Text('${day.high}° / ${day.low}°', style: const TextStyle(fontSize: 18)),
],
),
),
],
);
}
}
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,
);
}
}
Questa lezione include un breve quiz. Inizia la lezione per rispondere e tenere traccia dei tuoi progressi.
Tutte le lezioni di Dati e rete
3Quando le chiamate falliscono
Gestire gli errori con tryLanciare un errorePulire con finallyLo stato di errore di FutureBuilderUn pulsante per riprovare6Progetto: App meteo
App meteo: adessoApp meteo: i prossimi tre giorniEsercitati da solo: Compilatore Flutter online