Page 1 of 1

Es wurde ein Wert vom Typ „String“ erwartet, aber ein Wert vom Typ „Null“ erhalten.

Posted: 16 Jan 2025, 11:41
by Guest

Code: Select all

import 'package:flutter/material.dart';
import 'widgets/main_widget.dart';

import 'package:http/http.dart' as http;

import 'dart:async';

import 'dart:convert';

Future fetchWeather() async {

final zipCode = "180007";

final apiKey = "d415dc7d3cae2e2b8a722dca06eb9e88";

final requestUrl =
"http://api.openweathermap.org/data/2.5/weather?zip={zipCode},IN&units=imperial&appid={apiKey}";

final response = await http.get(Uri.parse(requestUrl));

return WeatherInfo.fromJson(jsonDecode(response.body));
}

class WeatherInfo {

final String location;

final double temp;

final double tempMin;

final double tempMax;

final String weather;

final int Humidity;

final double windspeed;

WeatherInfo(

{required this.location,

required this.temp,

required this.tempMin,

required this.tempMax,

required this.weather,

required this.Humidity,

required this.windspeed});

factory WeatherInfo.fromJson(Map json) {

return WeatherInfo(

location: json['name'],

temp: json['main']['temp'],

tempMin: json['main']['temp_min'],

tempMax: json['main']['temp_max'],

weather: json['weather']['description'],

Humidity: json['main']['humidity'],

windspeed: json['wind']['speed']);

}
}

void main() => runApp(MaterialApp(title: "Weather App", home: MyApp()));

class MyApp extends StatefulWidget {

@override

State createState() {

return _MyApp();

}
}

class _MyApp extends State {

late Future futureWeather;

@override

void initState() {

super.initState();

futureWeather = fetchWeather();
}

@override

Widget build(BuildContext context) {

return Scaffold(

body: FutureBuilder(

future: futureWeather,

builder: (context, Snapshot) {

if (Snapshot.hasData) {

return MainWidget(

location: Snapshot.data!.location,

temp: Snapshot.data!.temp,

tempMin: Snapshot.data!.tempMin,

tempMax: Snapshot.data!.tempMax,

weather: Snapshot.data!.weather,

Humidity: Snapshot.data!.Humidity,

windspeed: Snapshot.data!.windspeed);

} else if (Snapshot.hasError) {

return Center(

child: Text("${Snapshot.error}"),

);
}

return CircularProgressIndicator();
}));
}
}