Wetter-App: Wettersymbole
Teil des Abschnitts Daten und Netzwerk der Flutter-Journey von Coddy. Lektion 25 von 27.
Menschen erkennen eine Sonne schneller als das Wort Sunny. Verwandle jede Bedingung mit einer Funktion in ein Symbol und verwende es überall dort, wo eine Bedingung angezeigt wird.
Ein switch-Ausdruck wählt für jeden Fall einen Wert aus; für alle übrigen Fälle wird _ verwendet:
IconData iconFor(String condition) {
return switch (condition) {
'Sunny' => Icons.wb_sunny,
'Cloudy' => Icons.cloud,
_ => Icons.help_outline,
};
}Die Fälle müssen exakt mit dem Text des Servers übereinstimmen, einschließlich der Groß- und Kleinschreibung: 'sunny' würde niemals mit Sunny übereinstimmen. Der Fall _ sorgt dafür, dass die App weiterhin funktioniert, falls der Server eines Tages eine Bedingung sendet, mit der du nicht gerechnet hast.
Aufgabe
MittelFüge Symbole hinzu:
- eine
iconFor-Methode:SunnyistIcons.wb_sunny,CloudyistIcons.cloud,RainyistIcons.umbrella,SnowyistIcons.ac_unit, alles andereIcons.help_outline - unter der Stadt das Symbol für die aktuelle Bedingung, Größe
96,Colors.orange - am Anfang jeder Vorhersagezeile das Symbol des jeweiligen Tages, dann
16Pixel Abstand
Probier es selbst
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));
}
@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)),
const SizedBox(height: 32),
for (final day in weather.forecast)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 8),
child: Row(
children: [
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,
);
}
}
Diese Lektion enthält ein kurzes Quiz. Starte die Lektion, um es zu beantworten und deinen Fortschritt zu speichern.
Alle Lektionen in Daten und Netzwerk
2Ladebildschirme
Ein Spinner während des LadensFutureBuilder kennenlernenEinmalig in initState ladenDaten per Button neu ladenZum Aktualisieren nach unten ziehen5Datumsangaben und Preise
Datumsangaben mit DateFormatUhrzeiten mit DateFormatPreise mit NumberFormat3Wenn Aufrufe fehlschlagen
Fehler mit try abfangenEinen Fehler auslösenAufräumen mit finallyDer Fehlerzustand von FutureBuilderEine Erneut-versuchen-Schaltfläche6Projekt: Wetter-App
Wetter-App: JetztWetter-App: Die nächsten drei TageÜbe selbstständig: Online-Flutter-Compiler