Skip to content

About

This is a Second Project of making the Weather App by calling the Api with key to know about the flutter well

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Weather App

A small Flutter app that looks up current weather for a city through the APILayer / Weatherstack API and renders it in a dark, iOS-style (Cupertino) interface.

The whole application lives in one file: lib/main.dart (338 lines) — entry point, networking, state and UI are all defined there.

Highlights

  • Single-screen experience — type a city, press Search Weather (or hit Enter), see the result inline.
  • Cupertino design — CupertinoApp, CupertinoPageScaffold, CupertinoNavigationBar, CupertinoTextField and CupertinoButton.filled.
  • Metric units — requests are made with units=m; temperature is in °C and wind speed in km/h.
  • Explicit loading / error / success states — spinner, red error text and a two-card result panel.
  • Lifecycle-safe — every setState after the network call is guarded by mounted.

Demo

Optimized previews and recordings are stored in docs/media/:

Desktop IPhone
Weather app on iPhone Weather app on desktop

The original screen recordings are kept untouched in the project root:

Source recording Original size Optimized file Optimized size Reduction
/Users/tanushpatel/weather_app/Screen Recording iPhone 18 Pro 29-11-2026 at 3.06.14 PM.mp4 5.6 MB docs/media/iphone-demo.mp4 266 KB ~95%
/Users/tanushpatel/weather_app/Screen Recording 2026-11-29 at 3.08.56 PM.mov 3.9 MB docs/media/desktop-demo.mp4 246 KB ~94%

The space before PM in both original filenames is a narrow no-break space (U+202F), as produced by the macOS recorder. See Media conversion for the exact commands.

How the app works

Code map

Lines What they contain
1–10 Imports (dart:convert, flutter/cupertino.dart, http), endpoint URL and API key constants
12–14 main() — calls runApp(const WeatherApp())
16–26 WeatherApp — root CupertinoApp, banner disabled, WeatherHomePage as home
28–33 WeatherHomePage — stateful widget creating _WeatherHomePageState
35–41 State fields — controller, loading flag, error message, response map
42–103 getWeather(String city) — validation, HTTP request, response checks, error handling
105–109 dispose() — releases the TextEditingController
111–299 build() — the complete screen and its conditional states
301–337 weatherCard(...) — reusable metric card (icon, label, value)

Widget tree

WeatherApp (CupertinoApp)
└── WeatherHomePage (StatefulWidget)
    └── CupertinoPageScaffold (background: #101C35)
        ├── CupertinoNavigationBar ("Weather App")
        └── SafeArea
            └── SingleChildScrollView (padding: 20)
                └── Column
                    ├── Hero icon (cloud_sun_fill, 90)
                    ├── "Weather Forecast" title (28, bold)
                    ├── CupertinoTextField (city name)
                    ├── CupertinoButton.filled ("Search Weather")
                    ├── CupertinoActivityIndicator          ← when isLoading
                    ├── Error Text (systemRed)              ← when errorMessage != null
                    └── Result block                         ← when weatherData + current exist
                        ├── "City, Country" (25, bold)
                        ├── Weather icon (80)
                        ├── Temperature (55, weight 300)
                        ├── Description (uppercase, 16)
                        ├── "Feels like" (16)
                        └── Row → weatherCard × 2 (Humidity, Wind Speed)

State model

Field Type Role
cityController TextEditingController Holds the text field value; read on submit / button press
isLoading bool Drives the spinner and disables the search button
errorMessage String? User-facing error text; null means no error
weatherData Map<String, dynamic>? Full decoded API payload; null until the first successful response

Request lifecycle (getWeather)

  1. Validate — an empty / whitespace-only city sets "Please enter a city name." and returns without a request.
  2. Start loading — isLoading = true, errorMessage = null.
  3. Build URI — Uri.parse(apiUrl).replace(queryParameters: { access_key, query: city.trim(), units: 'm' }).
  4. Fetch — http.get(uri).timeout(const Duration(seconds: 15)).
  5. Validate success — HTTP 200 only; body must decode to a Map<String, dynamic>.
  6. Validate payload — a top-level error object is thrown with error['info']; missing current or location is also an error.
  7. Commit — weatherData = data if the widget is still mounted.
  8. Catch — any exception is displayed after stripping the Exception: prefix.
  9. Finish — finally clears isLoading (again, only when mounted).

Endpoint: https://api.apilayer.net/weatherstack/current (APILayer's Weatherstack "current" endpoint).

Fields consumed from the response:

location.name       location.country
current.temperature current.feelslike
current.humidity    current.wind_speed
current.weather_descriptions[0]

Visual design tokens

Token Value Used for
Background #101C35 Page and navigation bar
Surface #253653 Text field and metric cards
Accent #FFD166 Hero/result icons and card icons
Text white / systemGrey2 Primary values vs. secondary labels
Error systemRed Error message
Corner radius 15 / 18 Field + button / cards
Page padding 20 SingleChildScrollView
Spacing 25, 20, 15, 12, 10, 30 Vertical rhythm between sections

Error handling details

  • Non-200 responses become Server error: <status code>.
  • Timeout, DNS and JSON failures are caught by the same catch block and shown verbatim (with the Exception: prefix removed).
  • A malformed weather_descriptions value falls back to "Weather information".
  • Missing numeric fields render as -- / --°C.
  • mounted is checked before every post-await setState, so a disposed screen cannot cause a crash.
  • dispose() releases cityController.

Observations from the code

What is done well

  • Networking, validation and UI states are separated into clear steps inside one readable method.
  • The request is bounded by a 15-second timeout, so the spinner cannot hang forever.
  • The payload is shape-checked before use; a successful HTTP status alone is not trusted.
  • Async gaps are guarded with mounted, and the controller is disposed.
  • Null-safe fallbacks keep the UI intact when a field is missing.

Gaps and suggested improvements

  1. Security — hardcoded API key. apiKey is a literal at line 10. Anyone with the source (or this repository) can use it, and it is exposed in shipped binaries. Move it to an environment variable / --dart-define or proxy the call through a backend, and rotate the current key before publishing.
  2. Stale results on failure. A failed search does not clear weatherData, so the previous city's card remains visible together with the new error. Clear it (or keep it explicitly labelled as the last result) when an error occurs.
  3. The UI says "Forecast" but only shows current conditions. The endpoint is /current; there is no hourly/daily forecast data.
  4. Sample test is broken. test/widget_test.dart is still the Flutter counter template: it expects 0/1 and Icons.add in an app that has neither. Replace it with tests for empty input, error text, and a mocked successful response.
  5. Unused dependency. material_ui: ^1.1.0 is declared in pubspec.yaml and imported by the stale test, but main.dart does not use it.
  6. No cancel / debounce / focus handling. Rapid submissions can overlap; consider disabling input during loading, using a request token, and calling FocusScope.of(context).unfocus() after submit.
  7. Raw error strings. e.toString() can leak implementation details; map known failures to friendly messages and log details instead.
  8. No caching, retry, refresh or location lookup. A short-lived cache, pull-to-refresh and optional "use my location" would make the single screen much more useful.
  9. Fixed theme and free-form input. The palette is hard-coded (no light theme), input is not validated against a city list, and there are no semantics labels for assistive technologies.

Getting started

flutter pub get
flutter run

The app uses the key committed in lib/main.dart. To use your own key, replace the apiKey constant (preferably reading it from a build-time environment variable instead).

flutter analyze   # static checks
flutter test      # currently fails — see "Gaps and suggested improvements"

Media conversion

Both recordings are silent (no audio stream), so an audio-only format such as MP3 would contain nothing. They were kept as video and re-encoded for a small README-friendly footprint; poster frames were extracted as WebP.

# iPhone recording → lightweight MP4
ffmpeg -i "Screen Recording iPhone 18 Pro 29-11-2026 at 3.06.14 PM.mp4" \
  -an -vf "fps=30,scale=720:-2:flags=lanczos" \
  -c:v libx264 -preset slow -crf 30 -pix_fmt yuv420p -movflags +faststart \
  docs/media/iphone-demo.mp4

# Desktop recording → lightweight MP4
ffmpeg -i "Screen Recording 2026-11-29 at 3.08.56 PM.mov" \
  -an -vf "fps=30" \
  -c:v libx264 -preset slow -crf 30 -pix_fmt yuv420p -movflags +faststart \
  docs/media/desktop-demo.mp4

# Poster frames → WebP (replace <time> with 13 for iPhone, 8 for desktop)
ffmpeg -ss <time> -i <source> -frames:v 1 poster.png
cwebp -q 82 poster.png -o docs/media/<name>.webp

Settings used: H.264 CRF 30, slow preset, 30 fps cap, no audio, yuv420p, and fast-start moov atom for instant playback. The iPhone clip was downscaled from 1206×2622 to 720×1566; the desktop clip kept its native 472×954 resolution.

About

This is a Second Project of making the Weather App by calling the Api with key to know about the flutter well

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages