Menu
CoddyTech

날씨 앱: 현재 날씨

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

이 섹션에서는 완성된 앱 하나를 만들어 봅니다. 바로 날씨 앱입니다. 다음 다섯 개의 레슨에서는 현재 도시의 날씨, 앞으로 3일간의 날씨와 각각의 아이콘, ‘다시 시도’ 버튼이 있는 오류 화면, 그리고 도시 선택기를 보여 줍니다.

연습용 API에는 세 개의 도시가 있습니다. /weather/lisbon은 다음을 응답합니다.

{
  "city": "Lisbon",
  "temperature": 21,
  "condition": "Sunny",
  "forecast": [ ... ]
}

화면 상단부터 시작해, 이미 알고 있는 단계를 따라가세요. 데이터를 위한 클래스, 데이터를 가져와 디코딩하는 함수, initState에서 한 번 만드는 future, 그리고 세 가지 상태를 처리하는 FutureBuilder입니다. 파일 아래쪽에 있는 Weather 및 DayForecast 클래스와 해당 클래스의 fromJson은 미리 작성되어 있습니다. 이 레슨에서는 현재 날씨를 보여 주고, 예보는 다음 레슨에서 다룹니다.

challenge icon

챌린지

어려움

리스본의 날씨를 표시하세요:

  • loadWeather는 /weather/lisbon을 가져와 Weather.fromJson(jsonDecode(body))를 반환합니다
  • initState에서 future를 한 번 만듭니다
  • FutureBuilder<Weather>는 로드하는 동안 로딩 표시기를 보여 주고, 실패하면 Could not load: 와 오류를 보여 줍니다
  • 데이터가 있으면 도시(크기 32), 도 기호가 붙은 온도 21°(크기 72, 굵게), 날씨 상태(크기 24)를 Column에 표시합니다

직접 해보기

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> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Weather')),
      body: const Center(
        child: Text('The weather goes here'),
      ),
    );
  }
}

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 컴파일러