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

Issue

Hi i am working on a weather app i learnt from a course, everything was working fine till i start with the refactoring and it just got complicated the code show no error but when i hot restart the app it crash showing

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

in the console

i don’t even know where i went wrong with my code and i will like if someone can take a lot at the code below and how i can fix it:
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,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

this is the part from the location_screen.dart where i think i made a mistake i tried using jsonDecode(data) to see if that will fix it, but it did not, because i have already declared it somewhere else before :

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

I tried fixing it , but it did not work , i am actually a beginner on flutter, i think that is the reason why i am having this ,

so i will like someone to lead me on the right path..just incase if i encounter such in the future i can fix it myself thanks.enter image description here

Solution

in networking.dart you must return like this

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

since you used variable in loading_screen.dart

var weatherdata = await networkHelper.getData();

var weatherdata is expecting a value, thus null is returned

Answered By – Trend74X

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *