125 lines
2.9 KiB
Dart
125 lines
2.9 KiB
Dart
// Local
|
|
import '/var/secrets.dart';
|
|
import 'var/config.dart';
|
|
|
|
// Flutter / Dart
|
|
import 'package:flutter/material.dart';
|
|
import 'package:http/http.dart' as http;
|
|
import 'dart:convert';
|
|
|
|
void main() {
|
|
runApp(const MainApp());
|
|
}
|
|
|
|
final String loadText = "Loading...";
|
|
|
|
class MainApp extends StatefulWidget {
|
|
const MainApp({super.key});
|
|
|
|
@override
|
|
State<MainApp> createState() => _MainAppState();
|
|
}
|
|
|
|
class _MainAppState extends State<MainApp> {
|
|
String weather = loadText;
|
|
bool keepLoading = false;
|
|
DateTime lastLoadTime = DateTime.now().subtract(
|
|
Duration(seconds: limitRefreshSeconds),
|
|
);
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
_refreshWeather();
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
super.dispose();
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
Widget weatherLayout = Column(
|
|
children: [Text(weather), CircularProgressIndicator()],
|
|
);
|
|
|
|
if (weather == loadText) {
|
|
Future.delayed(Duration(seconds: 1), () {
|
|
setState(() {
|
|
keepLoading = true;
|
|
});
|
|
});
|
|
} else {
|
|
weatherLayout = Column(
|
|
children: [
|
|
TextButton.icon(
|
|
label: Text("Reload Weather"),
|
|
onPressed: () {
|
|
setState(() {
|
|
_refreshWeather();
|
|
});
|
|
},
|
|
),
|
|
Text(weather),
|
|
],
|
|
);
|
|
}
|
|
|
|
return MaterialApp(
|
|
home: Scaffold(
|
|
body: Center(
|
|
child: Column(children: [Text('Weather Today!'), weatherLayout]),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
// How to guide:
|
|
// https://openweathermap.org/current#zip
|
|
Future<String> _hitOpenWeather(String zipCode, String? countryCode) async {
|
|
countryCode ??= "US";
|
|
|
|
String url =
|
|
'https://api.openweathermap.org/data/2.5/forecast'
|
|
'?zip=$zipCode,$countryCode'
|
|
'&units=imperial'
|
|
'&appid=$openWeatherKey';
|
|
|
|
if (debug) debugPrint(url);
|
|
http.Response response = await http.get(Uri.parse(url));
|
|
|
|
String data = "";
|
|
if (response.statusCode == 200) {
|
|
data = response.body;
|
|
var decodedData = jsonDecode(data);
|
|
//if (debug) debugPrint(decodedData.toString());
|
|
data = decodedData.toString();
|
|
} else {
|
|
if (debug) debugPrint(response.statusCode.toString());
|
|
}
|
|
|
|
return data;
|
|
}
|
|
|
|
_callOpenWeather() async {
|
|
weather = await _hitOpenWeather("47630", "US");
|
|
}
|
|
|
|
_refreshWeather() {
|
|
var lastReloadSeconds = DateTime.now().difference(lastLoadTime).inSeconds;
|
|
if (debug) debugPrint("DEBUG: Refresh was $lastReloadSeconds seconds ago.");
|
|
|
|
if (lastReloadSeconds < limitRefreshSeconds) {
|
|
debugPrint("DEBUG: Skipping reload.");
|
|
// TODO / TBD: Show a toast / scaffold snackbar that it cannot reload yet,
|
|
// or change the button text to "Please wait X seconds!".
|
|
return;
|
|
}
|
|
|
|
weather = loadText;
|
|
_callOpenWeather();
|
|
lastLoadTime = DateTime.now();
|
|
}
|
|
}
|