[Flutter/Dart] OpenWeatherMap Api 로 날씨 받아오기

찌니·2022년 11월 22일
0
post-thumbnail

공공데이터를 사용하다가 받아오는 속도가 너무 느려서 api를 openWeather 로 변경하기로 했다..!

https://openweathermap.org/

가입하면 바로 Api key를 발급해줘서 그냥 가져다가 사용하면 된다
먼저 기본 설정으로 환경변수 파일 .env에 key 값을 넣어주었다 (url도 같이 넣어줌)


대충 이런 데이터가 오는데 가져오고 싶은 데이터만 골라서 모델을 만들어주었다
대충 기온, 최저기온, 최고기온, 하늘 상태, 하늘 상태 코드, 습도

먼저 api 통신을 위한 NetworkHelper를 만들어주고

날씨를 가져오기 위해서는 가져올 위치의 위경도가 필요한데, Geolocator를 사용하면 된다.
https://pub.dev/packages/geolocator

날씨를 가져오는 Weather service를 생성해준다.

(위치 받아오는 MyLocation 클래스에는 대충 이런게 들어있음)

쨋든 이렇게 위치와 키를 주면 데이터를 받아올 수 있다 (여기에서는 Provider에서 받아왔다)
생성한 모델과 데이터 형식을 참고해 데이터를 입맛에 맞춰 정제해준다.

이제 그냥 가져다 쓰면 된다 ~!~!~!

귀염,,

전체 코드


class NetworkHelper {
  static final NetworkHelper _instance = NetworkHelper._internal();
  factory NetworkHelper() => _instance;
  NetworkHelper._internal();

  Future getData(String url) async {
    http.Response response = await http.get(Uri.parse(url));

    if (response.statusCode == 200) {
      return jsonDecode(response.body);
    } else {
      print(response.statusCode);
    }
  }
}

class Weather {
  double? temp;
  double? tempMax;
  double? tempMin;
  String? condition;
  int? conditionId;
  int? humidity;

  Weather({this.temp, this.tempMax, this.tempMin, this.condition, this.conditionId, this.humidity});
  }
  
 
class OpenWeatherService {
  final String _apiKey = dotenv.env['openWeatherApiKey']!;
  final String _baseUrl = dotenv.env['openWeatherApiBaseUrl']!;

  Future getWeather() async {
    MyLocation myLocation = MyLocation();
    developer.log("myLocation called in network");
    try {
      await myLocation.getMyCurrentLocation();
    } catch (e) {
      developer.log("error : getLocation ${e.toString()}");
    }

    final weatherData = NetworkHelper().getData(
        '$_baseUrl?lat=${myLocation.latitude}&lon=${myLocation.longitude}&appid=$_apiKey&units=metric');
    return weatherData;
  }
}
  
enum LoadingStatus { completed, searching, empty }

class WeatherProvider with ChangeNotifier {
  final Weather _weather =
      Weather(temp: 20, condition: "Clouds", conditionId: 200, humidity: 50);
  Weather get weather => _weather;

  LoadingStatus _loadingStatus = LoadingStatus.empty;
  LoadingStatus get loadingStatus => _loadingStatus;

  String _message = "Loading...";
  String get message => _message;

  final OpenWeatherService _openWeatherService = OpenWeatherService();

  Future<void> getWeather() async {
    _loadingStatus = LoadingStatus.searching;

    final weatherData = await _openWeatherService.getWeather();
    if (weatherData == null) {
      _loadingStatus = LoadingStatus.empty;
      _message = 'Could not find weather. Please try again.';
    } else {
      _loadingStatus = LoadingStatus.completed;
      weather.condition = weatherData['weather'][0]['main'];
      weather.conditionId = weatherData['weather'][0]['id'];
      weather.humidity = weatherData['main']['humidity'];
      weather.temp = weatherData['main']['temp'];
      weather.temp = (weather.temp! * 10).roundToDouble() / 10;
    }

    notifyListeners();
  }
profile
찌니's develog

0개의 댓글