dart 对null调用了方法“[]”,接收方:空尝试呼叫:[](“主”)控制台错误

j0pj023g  于 2023-01-18  发布在  其他
关注(0)|答案(3)|浏览(108)

嗨,我正在做一个天气应用程序,我从一门课程中学到的,一切都很好,直到我开始与重构,它只是变得复杂的代码显示没有错误,但当我热启动应用程序时,它崩溃显示

The method '[]' was called on null.
Receiver: null
Tried calling: []("main")

在控制台中
我甚至不知道我哪里出了问题,我的代码,我会喜欢,如果有人可以采取很多在下面的代码,我如何可以修复它:网络.dart

import 'package:http/http.dart' as http;
import 'dart:convert';

class NetworkHelper {
  NetworkHelper(this.url);
  final String url;

  Future getData() async {
    http.Response response = await http.get(Uri.parse(url));
    if (response.statusCode == 200) {
      String data = response.body;
      var output = jsonDecode(data);
    } else {
      print(response.statusCode);
      print('not working');
    }
  }
}

正在加载屏幕.dart

import 'package:flutter/animation.dart';
import 'package:flutter/material.dart';
import 'package:clima/services/location.dart';
import 'package:clima/services/networking.dart';
import 'package:clima/screens/location_screen.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';

const apiKey = '4c6ffd8e4e647128123739045f48d839';

class LoadingScreen extends StatefulWidget {
  @override
  _LoadingScreenState createState() => _LoadingScreenState();
}

class _LoadingScreenState extends State<LoadingScreen> {
  @override
  double? latitude;
  double? longtitude;
  void initState() {
    super.initState();
    getLocationData();
  }

  void getLocationData() async {
    Location location = Location();
    await location.geolocation();
    latitude = location.latitude;
    longtitude = location.longtitude;
    NetworkHelper networkHelper = NetworkHelper(
        'https://api.openweathermap.org/data/2.5/weather?lat=$latitude&lon=$longtitude&appid=$apiKey&units=metric');
    var weatherdata = await networkHelper.getData();
    Navigator.push(context, MaterialPageRoute(builder: (context) {
      return LocationScreen(
        locationWeather: weatherdata,
      );
    }));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: SpinKitDoubleBounce(
          color: Colors.white,
          size: 100.0,
        ),
      ),
    );
  }
}

位置_屏幕.dart

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:clima/utilities/constants.dart';
import 'package:clima/services/weather.dart';

class LocationScreen extends StatefulWidget {
  final locationWeather;
  LocationScreen({this.locationWeather});
  @override
  _LocationScreenState createState() => _LocationScreenState();
}

class _LocationScreenState extends State<LocationScreen> {
  WeatherModel weather = WeatherModel();
  int? temperature;
  String? weatherIcon;
  String? cityName;
  String? weatherMessage;
  @override
  void initState() {
    UpdateUi(widget.locationWeather);
    super.initState();
  }

  void UpdateUi(dynamic weatherData) {
    setState(() {
      double temp = weatherData['main']['temp'];
      temperature = temp.toInt();
      var condition = weatherData['weather'][0]['id '];
      cityName = weatherData['name'];
      weatherMessage = weather.getMessage(temperature!);
      weatherIcon = weather.getWeatherIcon(condition);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('images/location_background.jpg'),
            fit: BoxFit.cover,
            colorFilter: ColorFilter.mode(
                Colors.white.withOpacity(0.8), BlendMode.dstATop),
          ),
        ),
        constraints: BoxConstraints.expand(),
        child: SafeArea(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  FlatButton(
                    onPressed: () {},
                    child: Icon(
                      Icons.near_me,
                      size: 50.0,
                    ),
                  ),
                  FlatButton(
                    onPressed: () {},
                    child: Icon(
                      Icons.location_city,
                      size: 50.0,
                    ),
                  ),
                ],
              ),
              Padding(
                padding: EdgeInsets.only(left: 15.0),
                child: Row(
                  children: <Widget>[
                    Text(
                      weatherIcon!,
                      style: kTempTextStyle,
                    ),
                    Text(
                      '☀️',
                      style: kConditionTextStyle,
                    ),
                  ],
                ),
              ),
              Padding(
                padding: EdgeInsets.only(right: 15.0),
                child: Text(
                  "$weatherMessage in $cityName",
                  textAlign: TextAlign.right,
                  style: kMessageTextStyle,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

这是location_screen.dart中的一部分,我认为我犯了一个错误,我尝试使用jsonDecode(data)来查看是否可以修复它,但它没有,因为我之前已经在其他地方声明了它:

void UpdateUi(dynamic weatherData) {
    setState(() {
      double temp = weatherData['main']['temp'];
      temperature = temp.toInt();
      var condition = weatherData['weather'][0]['id '];
      cityName = weatherData['name'];
      weatherMessage = weather.getMessage(temperature!);
      weatherIcon = weather.getWeatherIcon(condition);
    });
  }

我试着修复它,但它没有工作,我实际上是一个初学者对Flutter,我想这就是为什么我有这个,
所以我希望有人能带领我走上正确的道路。。以防万一,如果我遇到这样的在未来,我可以修复它自己thanksider

f0brbegy

f0brbegy1#

在networking.dart中,您必须这样返回

String data = response.body;
var output = jsonDecode(data);
return output;

因为您在loading_screen.dart中使用了变量

var weatherdata = await networkHelper.getData();

var weatherdata需要一个值,因此返回null

2lpgd968

2lpgd9682#

请检查您的主.dart文件,确保您没有解析与主页相同的位置屏幕。可能是在导航器推送过程中出错。

cx6n0qe3

cx6n0qe33#

很抱歉问这个问题,但请如果你已经解决了这个错误,请告诉我前进的方向,因为我也与此堆栈

相关问题