Menu
CoddyTech

Wetter-App: Die nächsten drei Tage

Teil des Abschnitts Daten und Netzwerk der Flutter-Journey von Coddy. Lektion 24 von 27.

Die Antwort für eine Stadt enthält auch eine Vorhersage: eine JSON-Liste innerhalb des Objekts, ein Eintrag pro Tag.

"forecast": [
  {"date": "2026-10-20", "condition": "Cloudy", "high": 22, "low": 15},
  ...
]

Eine Liste innerhalb eines Objekts wird genauso gelesen wie eine eigenständige Liste: Hole sie mit as List<dynamic> heraus und wende dann auf jeden Eintrag sein eigenes fromJson an. Sieh dir Weather.fromJson am Ende der Datei an: Dort geschieht das bereits, daher ist weather.forecast eine List<DayForecast>.

final days = json['forecast'] as List<dynamic>;

forecast: days
    .map((day) => DayForecast.fromJson(day as Map<String, dynamic>))
    .toList(),

Jeder Tag hat ein DateTime. DateFormat('EEEE') wandelt es in den ausgeschriebenen Namen des Wochentags um, Tuesday. Eine for-Schleife in den untergeordneten Elementen von Column erzeugt eine Zeile pro Tag.

challenge icon

Aufgabe

Mittel

Zeige unter dem aktuellen Wetter die nächsten drei Tage:

  • import package:intl/intl.dart
  • nach einer SizedBox(height: 32) eine Row pro Tag: den Wochentag mit DateFormat('EEEE') in einem Expanded, danach Höchst- und Tiefsttemperatur als 22° / 15°
  • gib jeder Zeile links und rechts 32 Pixel Abstand

Probier es selbst

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,
    );
  }
}
quiz iconTeste dich selbst

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

Übe selbstständig: Online-Flutter-Compiler