【问题标题】:The method '[]' was called on null. Receiver: null Tried calling: []("main") console error在 null 上调用了方法“[]”。接收方:null 尝试调用:[]("main") 控制台错误
【发布时间】:2022-01-03 00:39:32
【问题描述】:

嗨,我正在开发一个从课程中学到的天气应用程序,一切正常,直到我开始重构,它变得复杂了,代码显示没有错误,但是当我热重启应用程序时,它会崩溃显示

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

在控制台中

我什至不知道我的代码哪里出了问题,如果有人可以在下面的代码中花很多时间以及如何解决它,我会很高兴: networking.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');
    }
  }
}

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

location_screen.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 dart dart-null-safety


    【解决方案1】:

    在networking.dart中你必须像这样返回

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

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

    var weatherdata = await networkHelper.getData();
    

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

    【讨论】:

      猜你喜欢
      • 2021-06-01
      • 2022-01-22
      • 2021-08-26
      • 2020-12-06
      • 2021-01-14
      • 2020-05-24
      • 2022-08-05
      • 2021-08-08
      • 2020-03-01
      相关资源
      最近更新 更多