如何处理“ getter'microsecondsSinceEpoch'在null上被调用。”错误?

问题描述 投票:0回答:2

我认为错误来自displayBackground()方法。我最近更改了代码,以从“ sunrise_sunset.dart”包中获取日出和日落。在此之前,我已经硬编码了日出和日落时间。

displayBackground()-这将根据当前时间更改背景图像。

import 'pa

    ckage:flutter/material.dart';
    import 'package:intl/intl.dart';
    import 'GetLocation.dart';
    import 'package:http/http.dart' as http;
    import 'dart:convert';
    import 'package:sunrise_sunset/sunrise_sunset.dart';

    void main() => runApp(WeatherApp());

    class WeatherApp extends StatefulWidget {
      @override
      _WeatherAppState createState() => _WeatherAppState();
    }

    class _WeatherAppState extends State<WeatherApp> {
      var apiKey = '5f10958d807d5c7e333ec2e54c4a5b16';
      var description;
      var temp;
      var city;
      var sunrise;

      var sunRise;
      var sunSet;
      var sunRiseEnd;
      var sunSetEnd;
      var formattedSunRise;
      var formattedSunSet;
      var newsunRiseEnd;
      var newsunSetEnd;
      var sunRise_sunSet_time;

      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(displayBackground()),
              ),
            ),
            child: Scaffold(
              backgroundColor: Colors.transparent,
              body: Column(
                children: <Widget>[
                  Container(
                    margin: EdgeInsets.only(top: 80),
                    child: Text(
                      'Your Location',
                      style: TextStyle(fontSize: 20, color: Colors.white),
                    ),
                  ),
                  Container(
                    color: Colors.transparent,
                    margin: EdgeInsets.symmetric(horizontal: 50),
                    child: Row(
                      children: <Widget>[
                        Container(
                          child: Text(
                            '${city.toString()}',
                            style: TextStyle(fontSize: 30, color: Colors.white),
                          ),
                        ),
                        SizedBox(width: 50),
                        Container(
                          child: Padding(
                            padding: const EdgeInsets.all(16.0),
                            child: Icon(
                              Icons.location_on,
                              color: Colors.white,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Card(
                    color: Colors.transparent,
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: ListTile(
                        leading: Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Icon(
                            Icons.wb_sunny,
                            color: Colors.white,
                          ),
                        ),
                        title: Center(
                          child: Text(
                            '$temp',
                            style: TextStyle(fontSize: 20, color: Colors.white),
                          ),
                        ),
                        subtitle: Center(
                          child: Text(
                            '$description',
                            style: TextStyle(color: Colors.white),
                          ),
                        ),
                      ),
                    ),
                  ),
                  Container(
                    child: Center(
                      child: FlatButton(
                          child: Text(
                            'Get Weather Info',
                            style: TextStyle(color: Colors.white),
                          ),
                          color: Colors.blueGrey,
                          onPressed: () {
                            setState(() {
                              getLocation();
                            });
                          }),
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      }

      // display background images based on current time
      displayBackground() {
        var now = DateTime.now();

        print('im here...$formattedSunRise');
        print(formattedSunSet);

        if ((now.isAfter(sunRise)) || (now.isBefore(sunRiseEnd))) {
          return 'images/Moon.png';
        } else if ((now.isAfter(sunRiseEnd)) || (now.isBefore(sunSet))) {
          return 'images/Sun.png';
        } else if ((now.isAfter(sunSet)) || (now.isBefore(sunSetEnd))) {
          return 'images/Moon.png';
        } else if ((now.isAfter(sunSetEnd)) || (now.isBefore(sunRise))) {
          return 'images/Blood.png';
        }
        return null;
      }

      //get location
      void getLocation() async {
        Getlocation getlocation = Getlocation();
        await getlocation.getCurrentLocation();

        print(getlocation.latitude);
        print(getlocation.longitude);
        print(getlocation.city);
        city = getlocation.city;
        getTemp(getlocation.latitude, getlocation.longitude);
      }

      //Get current temp
      Future<void> getTemp(double lat, double lon) async {
        http.Response response = await http.get(
            'https://api.openweathermap.org/data/2.5/weather?lat=$lat&lon=$lon&appid=$apiKey&units=metric');
        // print(response.body);

        sunRise_sunSet_time = await SunriseSunset.getResults(
            date: DateTime.now(), latitude: lat, longitude: lon);

        sunRise = sunRise_sunSet_time.data.sunrise;
        sunSet = sunRise_sunSet_time.data.sunset;

        formattedSunRise = DateFormat.Hm().format(sunRise);
        formattedSunSet = DateFormat.Hm().format(sunSet);

        sunRiseEnd = sunRise.add(new Duration(hours: 1));
        sunSetEnd = sunSet.add(new Duration(hours: 1));

        var dataDecoded = jsonDecode(response.body);

        setState(() {
          description = dataDecoded['weather'][0]['description'];
          temp = dataDecoded['main']['temp'];
          sunrise = dataDecoded['sys']['sunrise'];
        });

        print(temp);
        print(sunrise);
      }
    }

错误:

Performing hot reload...
Syncing files to device Android SDK built for x86...
I/flutter ( 9310): im here...null
I/flutter ( 9310): null

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building WeatherApp(dirty, state: _WeatherAppState#c4248):
The getter 'microsecondsSinceEpoch' was called on null.
Receiver: null
Tried calling: microsecondsSinceEpoch

The relevant error-causing widget was: 
  WeatherApp file:///C:/Users/aldo0/Desktop/Learn_Flutter/my_weather_app/lib/main.dart:8:23
When the exception was thrown, this was the stack: 
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
#1      DateTime.isAfter (dart:core-patch/date_patch.dart:87:50)
#2      _WeatherAppState.displayBackground (package:com/main.dart:135:15)
#3      _WeatherAppState.build (package:com/main.dart:40:31)
#4      StatefulElement.build (package:flutter/src/widgets/framework.dart:4619:28)
...
════════════════════════════════════════════════════════════════════════════════════════════════════
Reloaded 1 of 626 libraries in 383ms.
flutter dart flutter-layout
2个回答
0
投票

这里您正在发生错误

var dataDecoded = jsonDecode(response.body);

最有可能您的响应类型是字符串。


0
投票

displayBackground功能不应为async。异步函数返回Future。通过不指定返回类型,它假定函数将返回Future<dynamic>

将功能更改为此:

  String displayBackground() {
    var now = DateTime.now();

    print('im here...$formattedSunRise');
    print(formattedSunSet);

    if ( (now.isAfter(sunRise)) || (now.isBefore(sunRiseEnd)) ){
      return 'images/Moon.png';
    } else if((now.isAfter(sunRiseEnd)) || (now.isBefore(sunSet))){
      return 'images/Sun.png';
    } else if((now.isAfter(sunSet)) || (now.isBefore(sunSetEnd))){
      return 'images/Moon.png';
    } else if((now.isAfter(sunSetEnd)) || (now.isBefore(sunRise))){
      return 'images/Blood.png';
    }
    return null; // default return statement

  }
© www.soinside.com 2019 - 2024. All rights reserved.