weather_service.dart
Код: Выделить всё
import 'dart:convert';
import 'package:testapp/models/weather_model.dart';
import 'package:http/http.dart' as http;
class WeatherService {
//static const BASE_URL = 'https://api.openweathermap.org/data/2.5/forecast?q=Kutahya,tr&cnt=5&appid=e6080829dff63e16ef3e9756b2e4b0bd';
static const baseUrl = 'https://api.openweathermap.org/data/2.5/weather?';
final String apiKey; //The “final” keyword is used to declare variables whose values cannot be changed once assigned. When a variable is declared as final, it can only be assigned a value once, either at its declaration or within the constructor of the class.
WeatherService(this.apiKey){
Future getWeather(String city, String country) async {
final response = await http.get(Uri.parse('$baseUrl?q=$city,$country&appid=$apiKey&units=metric'));
if (response.statusCode == 200) {
return Weather.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to get Data');
}
}
}
}
Код: Выделить всё
import 'package:flutter/material.dart';
import 'package:testapp/models/weather_model.dart';
import 'package:testapp/services/weather_service.dart';
class WeatherPage extends StatefulWidget {
const WeatherPage({super.key});
@override
State createState() => _WeatherPageState();
}
class _WeatherPageState extends State {
//set api key
final _weatherService = WeatherService('e6080829dff63e16ef3e9756b2e4b0bd');
Weather? _weather; //imported from models/weather_model
//set city and country
String city = 'Kutahya'; //You may use Geolocator to get them automatically also.
String country = 'tr';
//get data
_fetchWeather() async {
try {
final weather = await _weatherService.getWeather(city, country);
setState(() {
_weather = weather;
});
}
catch (e){
print(e);
}
}
@override
Widget build(BuildContext context) {
return const Scaffold();
}
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... ss-flutter
Мобильная версия