【问题标题】:Flutter Error - 'package:flutter/src/painting/decoration_image.dart': Failed assertion: line 50 pos 15: 'image != null': is not true颤振错误 - 'package:flutter/src/painting/decoration_image.dart':断言失败:第 50 行 pos 15:'image != null':不正确
【发布时间】:2020-11-24 17:36:38
【问题描述】:

我在今天写的代码中遇到了这样的错误。你能帮帮我吗?

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

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

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

【问题讨论】:

  • 请检查您的 pubspec.yaml 文件
  • “pubspec.yaml”文件中的一切看起来都很好
  • 请不要删除您的 cmets,我是 codding 的初学者。 :)
  • 哦..好吧..我会尝试使用你的代码重现错误..我会在某个时候恢复,现在 Windows 正在做它的事情(更新):(
  • 好的,我在等你,谢谢..

标签: flutter dart mobile


【解决方案1】:

如果您从任何其他来源复制代码,建议您这样做

Flutter clean and Flutter run 

【讨论】:

    【解决方案2】:

    我试过了,效果很好!!

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

    让我知道它是否适合你。

    【讨论】:

    • 起初我能够看到一些图像,但突然它给出了同样的错误。你觉得我应该怎么做?
    • WeatherData 必须始终返回一个字符串,如“rain”、“thunderstorm”..以及您在图像映射中指定的所有这些..如果不匹配,它将引发相同的错误。如果您想检查哪个字符串抛出了错误,请尝试在函数中添加 print(weatherdata.name),然后查看名称是什么。
    • 如果它非常不确定,然后创建一个函数来处理它..创建一个返回 AssetImage 的函数..并且在该函数内部..chek 如果 isweatherloaded 为真..如果是,那么检查 weatherData.name 是否还返回您在图像映射中指定的字符串,如果返回则返回 images[weatherData.name],如果没有,则返回默认图像。
    • 嘿..我已经编辑了我的代码,我添加了一个 HandleError() 函数来处理错误。这有帮助吗?
    • 很高兴听到这个消息:)。快乐编码! :)
    猜你喜欢
    • 2020-07-01
    • 1970-01-01
    • 2021-05-04
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    • 2020-03-01
    • 2021-03-27
    • 2021-07-02
    相关资源
    最近更新 更多