// Local import '/var/secrets.dart'; import '/var/locals.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 createState() => _MainAppState(); } class _MainAppState extends State { String weather = loadText; bool keepLoading = false; DateTime lastLoadTime = DateTime.now().subtract(Duration(seconds: 5)); @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 _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 < 5) { 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(); } }