颤振错误 - "包:颤振/src/painting/decoration_image.dart":断言失败:第 50 行 pos 15:"图像 != null":不正确



我今天写的代码中出现了这样的错误。你能帮我吗?

'package:flutter/src/painting/decoration_image.dart': Failed assertion: line 50 pos 15: 'image != null': is not true.

我正在做天气预报。我想根据天气的不同改变背景照片。但无论我做什么,我都无法解决这个问题。我看不到任何类似于我收到的这个错误的错误。我的项目截止时间很近。

我的代码在这里:(如果你愿意,我可以添加导入的库。(

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:location/location.dart';
import 'package:flutter/services.dart';
import 'package:uygulama1/Weather.dart';
import 'package:uygulama1/WeatherItem.dart';
import 'package:uygulama1/WeatherData.dart';
import 'package:uygulama1/ForecastData.dart';
//PROJECT'S ROOT
void main() {
runApp(MaterialApp(
title: "WeatherApp",
home: MyApp(),

));
}
//PROJECTS MAIN CLASS
class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return new MyAppState();
}

}
class MyAppState extends State<MyApp> {
bool isLoading = false;
WeatherData weatherData;
ForecastData forecastData;
Location _location = new Location();
String error;
@override
void initState() {
super.initState();
loadWeather();
}

Future<LocationData> getLocationData() async {
return await _location.getLocation();
}
// HERE IS PROBLEM
final Map<String, AssetImage> images = {
"rain": AssetImage("assets/images/rain.jpg"),
"clear": AssetImage("assets/images/clear.jpg"),
"thunderstorm": AssetImage("assets/images/thunderstorm.jpg"),
"drizzle": AssetImage("assets/images/drizzle.jpg"),
"snow": AssetImage("assets/images/snow.jpg"),
"clouds": AssetImage("assets/images/clouds.jpg"),
};


@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Weather App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
backgroundColor: Colors.tealAccent,
appBar: AppBar(
title: Text('Flutter Weather App'),
),
body: Center(
child: Column(mainAxisSize: MainAxisSize.min, children: <Widget>[
//BACKGROUND IMAGE

//HERE IS PROBLEM
Container(
decoration: BoxDecoration(
image: new DecorationImage(
image: weatherData == null
? images["clear"]
: images[weatherData.name],
fit: BoxFit.cover),
),
),
//END
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: weatherData != null
? Weather(weather: weatherData)
: Container(),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: isLoading
? CircularProgressIndicator(
strokeWidth: 2.0,
valueColor:
new AlwaysStoppedAnimation(Colors.black),
)
: IconButton(
icon: new Icon(Icons.refresh),
tooltip: 'Refresh',
onPressed: loadWeather,
color: Colors.black,
),
),
],
),
),
SafeArea(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
height: 200.0,
child: forecastData != null
? ListView.builder(
itemCount: forecastData.list.length,
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) => WeatherItem(
weather: forecastData.list.elementAt(index)))
: Container(),
),
),
)
]))),
);
}
loadWeather() async {
setState(() {
isLoading = true;

});
LocationData location;
try {
location = await getLocationData();
error = null;
} on PlatformException catch (e) {
if (e.code == 'PERMISSION_DENIED') {
error = 'Permission denied';
} else if (e.code == 'PERMISSION_DENIED_NEVER_ASK') {
error =
'Permission denied - please ask the user to enable it from the app settings';
}
location = null;
}
if (location != null) {
final lat = location.latitude;
final lon = location.longitude;
final weatherResponse = await http.get(
'https://api.openweathermap.org/data/2.5/weather?APPID=d89de3f0b2dedfe4f923f1e7f709953a&lat=${lat.toString()}&lon=${lon.toString()}');
final forecastResponse = await http.get(
'https://api.openweathermap.org/data/2.5/forecast?APPID=d89de3f0b2dedfe4f923f1e7f709953a&lat=${lat.toString()}&lon=${lon.toString()}');
if (weatherResponse.statusCode == 200 &&
forecastResponse.statusCode == 200) {
return setState(() {
weatherData =
new WeatherData.fromJson(jsonDecode(weatherResponse.body));
forecastData =
new ForecastData.fromJson(jsonDecode(forecastResponse.body));
isLoading = false;
});
}
}
setState(() {
isLoading = false;
});
}
}

这是我的天气数据类别:

class WeatherData {
final DateTime date;
final String name;
final double temp;
final String main;
final String icon;
WeatherData({this.date, this.name, this.temp, this.main, this.icon});
factory WeatherData.fromJson(Map<String, dynamic> json) {
return WeatherData(
date: new DateTime.fromMillisecondsSinceEpoch(json['dt'] * 1000,
isUtc: false),
name: json['name'],
temp: json['main']['temp'].toDouble(),
main: json['weather'][0]['main'],
icon: json['weather'][0]['icon'],
);
}
}

WeatherItem类别:

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:uygulama1/WeatherData.dart';
class WeatherItem extends StatelessWidget {
final WeatherData weather;
WeatherItem({Key key, @required this.weather}) : super(key: key);
@override
Widget build(BuildContext context) {
var temperature = (weather.temp - 273.15).round();
return Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(weather.name, style: new TextStyle(color: Colors.black)),
Text(weather.main,
style: new TextStyle(color: Colors.black, fontSize: 24.0)),
Text('${temperature.toString()}°C',
style: new TextStyle(color: Colors.black)),
Image.network(
'https://openweathermap.org/img/w/${weather.icon}.png'),
Text(new DateFormat.yMMMd().format(weather.date),
style: new TextStyle(color: Colors.black)),
Text(new DateFormat.Hm().format(weather.date),
style: new TextStyle(color: Colors.black)),
],
),
),
);
}
}

天气。飞镖:

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:uygulama1/WeatherData.dart';
class Weather extends StatelessWidget {
final WeatherData weather;
Weather({Key key, @required this.weather}) : super(key: key);
@override
Widget build(BuildContext context) {
var temperature = (weather.temp - 273.15).round();
return Column(
children: <Widget>[
Text(weather.name, style: new TextStyle(color: Colors.black)),
Text("n" + weather.main,
style: new TextStyle(color: Colors.black, fontSize: 32.0)),
Text("Temp: " + '${temperature.toString()}°C',
style: new TextStyle(color: Colors.black)),
Image.network('https://openweathermap.org/img/w/${weather.icon}.png'),
Text("Date: " + new DateFormat.yMMMd().format(weather.date),
style: new TextStyle(color: Colors.black)),
Text("Hour: " + new DateFormat.Hm().format(weather.date),
style: new TextStyle(color: Colors.black)),
],
);
}
}

预测数据。dart:

import 'package:uygulama1/WeatherData.dart';
class ForecastData {
final List list;
ForecastData({this.list});
factory ForecastData.fromJson(Map<String, dynamic> json) {
List list = new List();
for (dynamic e in json['list']) {
WeatherData w = new WeatherData(
date: new DateTime.fromMillisecondsSinceEpoch(e['dt'] * 1000,
isUtc: false),
name: json['city']['name'],
temp: e['main']['temp'].toDouble(),
main: e['weather'][0]['main'],
icon: e['weather'][0]['icon']);
list.add(w);
}
return ForecastData(
list: list,
);
}
}

pubspec.yaml文件:

name: uygulama1
description: A new Flutter project.
publish_to: 'none'
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
http: ^0.11.3+16
intl: ^0.15.6
location: ^3.0.0
flutter_map: ^0.10.1
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
assets:
- assets/images/
uses-material-design: true

这是我的GitHub链接:https://github.com/mahmutcankurt1/FlutterWeatherApp

我试过了,它很管用!!

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:location/location.dart';
import 'package:flutter/services.dart';
import 'package:uygulama1/Weather.dart';
import 'package:uygulama1/WeatherItem.dart';
import 'package:uygulama1/WeatherData.dart';
import 'package:uygulama1/ForecastData.dart';
//PROJECT'S ROOT
void main() {
runApp(MaterialApp(
title: "WeatherApp",
home: MyApp(),
));
}
//PROJECTS MAIN CLASS
class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return new MyAppState();
}
}
class MyAppState extends State<MyApp> {
bool isLoading = false;
WeatherData weatherData;
ForecastData forecastData;
Location _location = new Location();
String error;
@override
void initState() {
super.initState();
triggerLoadFunction();
}
Future<LocationData> getLocationData() async {
return await _location.getLocation();
}
bool isweatherDataLoaded = false;
triggerLoadFunction() async {
await loadWeather();
}

// HERE IS PROBLEM
final Map<String, AssetImage> images = {
"rain": AssetImage("assets/images/rain.jpg"),
"clear": AssetImage("assets/images/clear.jpg"),
"thunderstorm": AssetImage("assets/images/thunderstorm.jpg"),
"drizzle": AssetImage("assets/images/drizzle.jpg"),
"snow": AssetImage("assets/images/snow.jpg"),
"clouds": AssetImage("assets/images/clouds.jpg"),
};
AssetImage HandleError(){
if(images.containsKey(weatherdata.name){
return images[weatherdata.name];
}else {
return images["a default image when the exact weather image is not available."];
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Weather App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
backgroundColor: Colors.tealAccent,
appBar: AppBar(
title: Text('Flutter Weather App'),
),
body: Center(
child: Column(children: <Widget>[
//BACKGROUND IMAGE
Container(
height: 90.0,
width: 120.0,
decoration: BoxDecoration(
image: DecorationImage(
image: isweatherDataLoaded //this
? HandleError()
: images["clear"],
fit: BoxFit.fill,
),
shape: BoxShape.circle,
),
),

Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: weatherData != null
? Weather(weather: weatherData)
: Container(),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: isLoading
? CircularProgressIndicator(
strokeWidth: 2.0,
valueColor:
new AlwaysStoppedAnimation(Colors.black),
)
: IconButton(
icon: new Icon(Icons.refresh),
tooltip: 'Refresh',
onPressed: () async {
await loadWeather();
},
color: Colors.black,
),
),
],
),
),
SafeArea(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
height: 200.0,
child: forecastData != null
? ListView.builder(
itemCount: forecastData.list.length,
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) => WeatherItem(
weather: forecastData.list.elementAt(index)))
: Container(),
),
),
)
]))),
);
}
loadWeather() async {
setState(() {
isLoading = true;
isweatherDataLoaded = false;
});
LocationData location;
try {
location = await getLocationData();
error = null;
} on PlatformException catch (e) {
if (e.code == 'PERMISSION_DENIED') {
error = 'Permission denied';
} else if (e.code == 'PERMISSION_DENIED_NEVER_ASK') {
error =
'Permission denied - please ask the user to enable it from the app settings';
}
location = null;
}
if (location != null) {
final lat = location.latitude;
final lon = location.longitude;
final weatherResponse = await http.get(
'https://api.openweathermap.org/data/2.5/weather?APPID=d89de3f0b2dedfe4f923f1e7f709953a&lat=${lat.toString()}&lon=${lon.toString()}');
final forecastResponse = await http.get(
'https://api.openweathermap.org/data/2.5/forecast?APPID=d89de3f0b2dedfe4f923f1e7f709953a&lat=${lat.toString()}&lon=${lon.toString()}');
if (weatherResponse.statusCode == 200 &&
forecastResponse.statusCode == 200) {
return setState(() {
weatherData =
new WeatherData.fromJson(jsonDecode(weatherResponse.body));
isweatherDataLoaded = true;
forecastData =
new ForecastData.fromJson(jsonDecode(forecastResponse.body));
isLoading = false;
isweatherDataLoaded = true;
});
}
}
setState(() {
isLoading = false;
isweatherDataLoaded = true;
});
}
}

所以问题正是我之前所说的,你在initState中称之为,所以当创建应用程序状态时,它没有来自WeatherData类的数据,因此应用程序崩溃了。

现在,我所做的是,我使用一个布尔变量isweatherDataLoaded来检查天气数据是否已加载,并相应地显示图像,我还为容器提供了一个固定的高度和宽度,以便其正确显示。

让我知道它是否对你有效。

如果您从任何其他源复制代码,建议您执行

Flutter clean and Flutter run 

相关内容

  • 没有找到相关文章

最新更新