Main.dart
import 'package:flutter/material.dart';
import 'package:flutter_application_1/currentWeather.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: CurrentWeatherPage(),
);
}
}
型号/天气.dart
class Weather {
final double temp;
final double feelslike;
final double low;
final double high;
final double description;
Weather({ required this.temp, required this.feelslike, required this.low, required this.high, required this.description});
factory Weather.fromjson(Map<String, dynamic>json) {
return Weather(
temp: json['main']['temp'].toDouble(),
feelslike: json['main']['feels_like'].toDouble(),
low: json['main']['temp_min'].toDouble(),
high: json['main']['temp_max'].toDouble(),
description: json['weather'][0]['description'],
);
}
}
currentWeather.dart
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:flutter_application_1/models/weather.dart';
class CurrentWeatherPage extends StatefulWidget{
@override
_CurrentWeatherPageState createState() => _CurrentWeatherPageState();
}
class _CurrentWeatherPageState extends State<CurrentWeatherPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: FutureBuilder(
builder: (context, snapshot){
// ignore: unnecessary_null_comparison
if (snapshot != null){
Weather _weather = snapshot.data;
// ignore: unnecessary_null_comparison
if (_weather == null){
return Text("ERROR GETING WEATHER");
} else {
return weatherBox(_weather);
}
} else{
return CircularProgressIndicator();
}
},
future: getCurrentWeather(),
),
),
);
}
Widget weatherBox(Weather _weather){
return Column(
children: <Widget>[
Text("${_weather.temp}°c"),
Text("${_weather.description}"),
Text("${_weather.feelslike}°c"),
Text("H:${_weather.high}°c L:${_weather.low}°c"),
],
);
}
}
Future getCurrentWeather() async {
Weather weather;
String city = "chennai";
String apikey = "safdgfdsgvf";
var url = Uri.parse("api.openweathermap.org/data/2.5/weather?q=$city&appid=$apikey");
final response = await http.get(url);
if (response.statusCode == 200) {
weather = Weather.fromjson(jsonDecode(response.body));
}else {
weather = Weather.fromjson(jsonDecode(response.body));
}
return weather;
}
当前Weather.dart
Weather _weather = snapshot.data;
snapshot.data显示错误:"Object?"类型的值无法分配给"Weather"类型的变量。尝试更改变量的类型,或将右侧类型强制转换为"Weather"。dart(invalid_assignment)
我该如何解决这个错误
您应该将snapshot.data
转换为Map<字符串,字符串>对象到Weather对象。
Weather _weatherl = Weather.fromjson(snapshot.data!.data());
// Output of this code is depend on how is your data structured in the database and Weather model you have defined here.