0

i want to get data from open weather api, and i keep getting this:

NoSuchMethodError: The method '[]' was called on null.Reciever: null tried calling:

is it a problem with the api or the code?the editor don't show any errors please help

my code:

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

void main() {
  runApp(MaterialApp(
    title: 'Weather',
    home: Weather(),
  ));
}

String api_key = 'the key';

Future<List> fetchData() async {
  var result = await http.get(Uri.http('http://api.openweathermap.org',
      'weather?lat=15.53804515&lon=32.52674103&appid=$api_key&units=metric'));
  return json.decode(result.body);
}

class Weather extends StatefulWidget {
  @override
  _WeatherState createState() => _WeatherState();
}

class _WeatherState extends State<Weather> {
  Color bgcolor;
  var data;
  @override
  void initState() {
    super.initState();
    fetchData().then((value) {
      setState() {
        data = value;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.blue,
        appBar: AppBar(
          title: Text('Weather App'),
          centerTitle: true,
        ),
        body: Center(
          child: Column(children: [
            Text(data['main']['temp']),
            Text(data['weather']['description']),
            Text(data['name'])
          ]),
        ));
  }
}
  • 1
    Can you show what you are getting in response? – Chirag Bargoojar May 21 '21 at 14:23
  • Does this answer your question? [What is a NoSuchMethod error and how do I fix it?](https://stackoverflow.com/questions/64049102/what-is-a-nosuchmethod-error-and-how-do-i-fix-it) – nvoigt May 21 '21 at 18:02
  • Your actual problem is that `data` is still null when you access it. See https://stackoverflow.com/questions/63017280/what-is-a-future-and-how-do-i-use-it – nvoigt May 21 '21 at 18:03

2 Answers2

2

fetchData is asynchronous, meaning it will take some time to execute and fetch that weather data. Until then, the variable "data" is uninitialized and thus null. Try adding a check for if data is null, then return a loading page or CircularProgressIndicator.

Kris
  • 3,091
  • 20
  • 28
1

Just add a simple null check -

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

void main() {
  runApp(MaterialApp(
    title: 'Weather',
    home: Weather(),
  ));
}

String api_key = 'the key';

Future<List> fetchData() async {
  var result = await http.get(Uri.http('http://api.openweathermap.org',
      'weather?lat=15.53804515&lon=32.52674103&appid=$api_key&units=metric'));
  return json.decode(result.body);
}

class Weather extends StatefulWidget {
  @override
  _WeatherState createState() => _WeatherState();
}

class _WeatherState extends State<Weather> {
  Color bgcolor;
  var data;
  @override
  void initState() {
    super.initState();
    fetchData().then((value) {
      setState() {
        data = value;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.blue,
        appBar: AppBar(
          title: Text('Weather App'),
          centerTitle: true,
        ),
        body: Center(
          child: data == null
            ? CircularProgressIndicator()
            : Column(children: [
            Text(data['main']['temp']),
            Text(data['weather']['description']),
            Text(data['name'])
          ]),
        ));
  }
}
robben
  • 637
  • 1
  • 7
  • 14