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

플러터 앱에서 GET 메소드를 사용하여 날씨 정보를 가져오는 방법은 다음과 같습니다:

  1. http 패키지를 추가합니다. pubspec.yaml 파일에 아래와 같은 의존성을 추가합니다:

    dependencies:
      http: ^0.13.4
    
  2. 날씨 데이터를 가져올 API의 URL을 정의합니다. 예를 들어, OpenWeatherMap API를 사용한다면 아래와 같이 URL을 정의할 수 있습니다:

    final String apiUrl = 'https://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}';
    

    {city} 부분은 도시 이름으로 바꿀 예정이며, {API_KEY}는 OpenWeatherMap API 키로 바꿀 예정입니다.

  3. GET 메소드를 통해 날씨 데이터를 가져오는 함수를 작성합니다. 아래는 예시입니다:

    Future<WeatherData> fetchWeatherData(String city) async {
      final response = await http.get(Uri.parse(apiUrl.replaceFirst('{city}', city).replaceFirst('{API_KEY}', apiKey)), headers: {
        'Content-Type': 'application/json',
      });
    
      if (response.statusCode == 200) {
        return WeatherData.fromJson(jsonDecode(response.body));
      } else {
        throw Exception('Failed to fetch weather data');
      }
    }
    

    위 코드는 WeatherData 모델을 사용하여 API 응답 데이터를 파싱하고 반환합니다. jsonDecode() 함수를 사용하여 JSON 응답을 파싱합니다.

  4. 날씨 데이터를 화면에 표시하는 방식은 개발자의 선택에 따라 다를 수 있습니다. 예를 들어, Text 위젯을 사용하여 날씨 정보를 화면에 표시할 수 있습니다.

    FutureBuilder<WeatherData>(
      future: fetchWeatherData('Seoul'),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return Text('${snapshot.data.temperature}℃');
        } else if (snapshot.hasError) {
          return Text('Failed to fetch weather data');
        } else {
          return CircularProgressIndicator();
        }
      },
    )
    

    FutureBuilder 위젯을 사용하여 비동기 데이터를 처리하고, snapshot 객체의 상태에 따라 화면에 적절한 위젯을 표시합니다.

이렇게 하면 플러터 앱에서 GET 메소드를 사용하여 날씨 정보를 가져올 수 있습니다. 다른 API를 사용한다면 API의 사용 방법에 따라 조금씩 다를 수 있으니 API 문서를 참고하시기 바랍니다.