[flutter] 플러터에서 GET 메소드를 사용하여 지역별 날씨 정보를 가져오는 방법은 무엇인가요?

먼저, http 패키지를 사용하여 GET 요청을 보내야 합니다. http 패키지를 사용하려면 http 패키지를 pubspec.yaml 파일에 추가해야 합니다.

dependencies:
  flutter:
    sdk: flutter
  http: ^0.13.3

이제 코드에서 http 패키지를 가져오고 GET 요청을 보내는 방법을 알아보겠습니다. 아래의 예제 코드를 참고하세요.

import 'package:http/http.dart' as http;
import 'dart:convert';

Future<Map<String, dynamic>> fetchWeatherData(String city) async {
  final url = Uri.parse('http://api.openweathermap.org/data/2.5/weather?q=$city&appid=YOUR_API_KEY');
  final response = await http.get(url);

  if (response.statusCode == 200) {
    return jsonDecode(response.body);
  } else {
    throw Exception('Failed to fetch weather data');
  }
}

void main() async {
  try {
    Map<String, dynamic> weatherData = await fetchWeatherData('Seoul');

    String temperature = weatherData['main']['temp'].toString();
    String description = weatherData['weather'][0]['description'];

    print('Temperature: $temperature');
    print('Description: $description');
  } catch (e) {
    print(e);
  }
}

위의 코드에서 fetchWeatherData 함수는 GET 요청을 보내고, 응답을 JSON으로 파싱하여 날씨 데이터를 반환합니다. main 함수에서는 fetchWeatherData 함수를 호출하고, 반환된 데이터에서 온도와 날씨 설명을 가져와 출력합니다. 여기서 YOUR_API_KEY를 실제로 발급받은 OpenWeatherMap API 키로 대체해야 합니다.

위의 코드는 간단한 예제로, OpenWeatherMap API를 사용하여 날씨를 가져옵니다. 실제로 사용하는 경우에는 API 키를 안전하게 보관하고, 다른 예외 상황에 대한 처리를 추가하는 것이 좋습니다.