Files
wetterApp/lib/screens/main_weather_view.dart
T
2022-09-03 21:36:18 +02:00

81 lines
2.5 KiB
Dart

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../components/compact_weather_data.dart';
import '../models/daily_weather_model.dart';
import '../services/brightsky_api_service.dart';
class MainWeatherView extends StatefulWidget {
final double lat;
final double lon;
const MainWeatherView(this.lat, this.lon, {Key? key}) : super(key: key);
@override
State<MainWeatherView> createState() => _MainWeatherViewState();
}
class _MainWeatherViewState extends State<MainWeatherView>
with AutomaticKeepAliveClientMixin<MainWeatherView> {
SharedPreferences? prefs;
int _daysToLoad = 7;
late Future<List<DailyWeatherModel>> dailyWeather;
@override
bool get wantKeepAlive => true;
@override
void initState() {
super.initState();
initializePreferences();
dailyWeather = BrightSkyAPI.fetchForecastForTimeRange(
DateTime.now(), _daysToLoad, widget.lat, widget.lon);
}
Future<void> initializePreferences() async {
prefs = await SharedPreferences.getInstance();
setState(() {
_daysToLoad = prefs!.getInt("daysToLoad") ?? 7;
});
}
@override
Widget build(BuildContext context) {
super.build(context);
return RefreshIndicator(
onRefresh: () {
return Future(() {
setState(() {
_daysToLoad = prefs?.getInt("daysToLoad") ?? 7;
dailyWeather = BrightSkyAPI.fetchForecastForTimeRange(
DateTime.now(), _daysToLoad, widget.lat, widget.lon);
});
});
},
child: SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(),
child: Center(
child: FutureBuilder<List<DailyWeatherModel>>(
future: BrightSkyAPI.fetchForecastForTimeRange(
DateTime.now(), _daysToLoad, widget.lat, widget.lon),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Column(
children: snapshot.data!
.map((e) => Padding(
padding: const EdgeInsets.symmetric(vertical: 5),
child: CompactWeatherData(e)))
.toList());
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
),
),
));
}
}