From c2537f78cd3a9624b88d293a4cdcd69b5ffb61ba Mon Sep 17 00:00:00 2001 From: Hyperling Date: Fri, 25 Apr 2025 07:54:20 -0700 Subject: [PATCH] Project is successfully hitting the weather API and returning the response to the screen after the async method finishes. Yay!! --- lib/main.dart | 73 ++++++++++++++++++++++++++++++++++++++++++++++++--- pubspec.yaml | 3 ++- 2 files changed, 72 insertions(+), 4 deletions(-) diff --git a/lib/main.dart b/lib/main.dart index a725658..7ef348f 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,20 +1,87 @@ +// Local +import 'package:com_hyperling_buddy_website/secrets.dart'; + +// Flutter / Dart import 'package:flutter/material.dart'; +import 'package:http/http.dart' as http; +import 'dart:convert'; void main() { runApp(const MainApp()); } -class MainApp extends StatelessWidget { +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; + + @override + void initState() { + super.initState(); + _callOpenWeather(); + } + + @override + void dispose() { + weather = loadText; + super.dispose(); + } + @override Widget build(BuildContext context) { - return const MaterialApp( + if (weather == loadText) { + Future.delayed(Duration(seconds: 1), () { + setState(() { + keepLoading = true; + }); + }); + } + + return MaterialApp( home: Scaffold( body: Center( - child: Text('Hello World!'), + child: Column(children: [Text('Hello World!'), Text(weather)]), ), ), ); } + + // How to guide: + // https://openweathermap.org/current#zip + Future _hitOpenWeather(String zipCode, String? countryCode) async { + countryCode ??= "US"; + + http.Response response = await http.get( + Uri.parse( + 'https://api.openweathermap.org/data/2.5/forecast' + '?zip=$zipCode,$countryCode' + '&units=imperial' + '&appid=$openWeatherKey', + ), + ); + + String data = ""; + if (response.statusCode == 200) { + data = response.body; + var decodedData = jsonDecode(data); + print(decodedData); + data = decodedData.toString(); + } else { + print(response.statusCode); + } + + return data; + } + + _callOpenWeather() async { + weather = await _hitOpenWeather("47630", "US"); + } } diff --git a/pubspec.yaml b/pubspec.yaml index c23c7da..020c36a 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,5 +1,5 @@ name: com_hyperling_buddy_website -description: "A new Flutter project." +description: "Buddy, a weather-focused API frontend." publish_to: 'none' version: 0.1.0 @@ -9,6 +9,7 @@ environment: dependencies: flutter: sdk: flutter + http: ^1.3.0 dev_dependencies: flutter_test: