Menu
CoddyTech

날씨 앱: 날씨 아이콘

Coddy Flutter 여정의 데이터와 네트워크 섹션에 포함된 레슨. 27개 중 25번째.

사람들은 Sunny라는 단어보다 태양 아이콘을 더 빨리 알아봅니다. 조건마다 하나의 함수로 아이콘을 지정하고, 조건이 표시되는 곳마다 사용하세요.

switch 표현식은 각 case에 해당하는 값을 선택하며, 그 외의 모든 경우에는 _를 사용합니다.

IconData iconFor(String condition) {
  return switch (condition) {
    'Sunny' => Icons.wb_sunny,
    'Cloudy' => Icons.cloud,
    _ => Icons.help_outline,
  };
}

각 case는 대소문자까지 포함해 서버의 텍스트와 정확히 일치해야 합니다. 'sunny'는 Sunny와 일치하지 않습니다. _ case를 사용하면 서버가 언젠가 예상하지 못한 조건을 보내더라도 앱이 계속 작동합니다.

challenge icon

챌린지

중급

아이콘을 추가하세요:

  • iconFor 메서드: Sunny는 Icons.wb_sunny, Cloudy는 Icons.cloud, Rainy는 Icons.umbrella, Snowy는 Icons.ac_unit, 그 외의 경우는 Icons.help_outline
  • 도시 아래에 현재 상태의 아이콘을 크기 96으로 표시하고, 색상은 Colors.orange로 설정하세요
  • 각 예보 행의 시작 부분에 해당 날짜의 아이콘을 표시한 다음 16픽셀 간격을 두세요

직접 해보기

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,
    );
  }
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

데이터와 네트워크의 모든 레슨

직접 연습해 보세요: 온라인 Flutter 컴파일러