**Файл weather_sevice.dart**
import 'dart:convert';
import '../models_1/weather.dart';
import 'package:http/http.dart' as http;
class WeatherService {
static const String _apiKey = '0550fd81c802afc639d9da94fae9c6ee';
static Future<Weather> fetchCurrentWeather({query, String lat = '', String lon = ''}) async {
var url = 'https://api.openweathermap.org/data/2.5/weather?q=$query&lat=$lat&lon=$lon&appid=$_apiKey';
final response = await http.post(Uri.parse(url));
if(response.statusCode == 200){
return Weather.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to load weather');
}
}
static Future<List<Weather>> fetchHourlyWeather({query, String lat = '', String lon = ''}) async {
var url = 'https://api.openweathermap.org/data/2.5/weather?q=$query&lat=$lat&lon=$lon&appid=$_apiKey';
final response = await http.post(Uri.parse(url));
if(response.statusCode == 200){
final jsonData = jsonDecode(response.body);
final List<Weather> data = (jsonData['list'] as List<dynamic>)
.map((item) {
return Weather.fromJson(item);
}).toList();
return data;
} else {
throw Exception('Failed to load weather');
}
}
}
**Файл main.dart**
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:weather_forecast/state_3/weather_state.dart';
import 'bloc_5/weather_bloc.dart';
import 'components_6/main_screen_wrapper.dart';
import 'delegates_7/search_delegate.dart';
import 'event_4/weather_event.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primaryColorDark: Colors.white,
primaryColor: Colors.white,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
State<StatefulWidget> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late final weatherBlocProvider = BlocProvider.of<WeatherBloc>(context);
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => WeatherBloc(),
child: BlocBuilder<WeatherBloc, WeatherState>(
builder: (context, state) {
if (state is WeatherLoadSuccess) {
return Scaffold(
appBar: AppBar(
elevation: 0,
backgroundColor: const Color.fromRGBO(0, 0, 0, 0),
actions: [
IconButton(
icon: const Icon(Icons.search),
onPressed: () {
showSearch(
context: context, delegate: MySearchDelegate((query) {
BlocProvider.of<WeatherBloc>(context).add(WeatherRequested(city: query));
},BlocProvider.of<WeatherBloc>(context) as String));
},
)
],
),
body: Padding(
padding: const EdgeInsets.only(top: 64),
child: MainScreenWrapper(
weather: state.weather, hourlyWeather: state.hourlyWeather,
),
),
);
}
return const Scaffold(
body: Center(
child: CircularProgressIndicator()
),
);
},
),
);
}
}