首页 > 解决方案 > 颤振错误 - 'package:flutter/src/painting/decoration_image.dart':断言失败:第 50 行 pos 15:'image != 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;
    });
  }
}

这是我的 WEATHERDATA 课程:

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'],
    );
  }
}

天气项目类:

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)),
          ],
        ),
      ),
    );
  }
}

天气.dart:

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)),
      ],
    );
  }
}

ForecastData.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

标签: flutterdartmobile

解决方案


我试过这个,它工作!

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 来检查天气数据是否已加载,并相应地显示图像,我还为容器提供了固定的高度和宽度以使其正确显示。

让我知道它是否适合你。


推荐阅读