Home > Software design >  NoSuchMethodError (NoSuchMethodError: The method '[]' was called on null. Receiver: null T
NoSuchMethodError (NoSuchMethodError: The method '[]' was called on null. Receiver: null T

Time:03-30

I am trying to create an application and this application gets information from the open-meteo API. I keep on encountering some errors that don't know how to fix. Would appreciate any help!!

title: Text(snapshot.data[i].longitude), //This is the line that is producing the error

import 'dart:convert'; 
import 'dart:ffi';

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

void main() => runApp(MaterialApp( 
home: HomePage(), 
debugShowCheckedModeBanner: false, 
));

class HomePage extends StatefulWidget { 
@override 
_HomePageState createState() => _HomePageState(); 
}

class _HomePageState extends State<HomePage> { 
Future getUserData() async { 

var response = await http.get(Uri.parse( 'https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41&hourly=temperature_2m')); 
var jsonData = jsonDecode(response.body); 
List<User> users = [];

for (var u in (jsonData)) {
  User user = User(u['longitude'], u['latitude'], u['hourly'], u['time'],u['temperature']);
  users.add(user);
}

print(users.length);
return users;
}



@override 

Widget build(BuildContext context) { 
 return Scaffold( 
  appBar: AppBar( 
   title: Text('Rangers Tool'), 
), 
 body: Container( 
 child: Card( 
   child: FutureBuilder( 
 future: getUserData(), 
 builder: (context, AsyncSnapshot snapshot) { 
return ListView.builder(
              itemCount: snapshot.data?.length,
              itemBuilder: (context, i) {

 return ListTile( 
  title: Text(snapshot.data[i].longitude), 
  subtitle: Text(snapshot.data[i].latitude), 
); 
}); 
} 

}, 

))), ); } }

class User { 

final String longitude, latitude, hourly, time, temperature;

User(this.longitude, this.latitude, this.hourly, this.time, this.temperature); }

}

CodePudding user response:

You need to change a few things here. And then you need to add a check to make sure that data is there by checking the status of the snapshot before using it to build your list. Similar to this:

FutureBuilder(
    future: _fetchListItems(),
    builder:(context, AsyncSnapshot snapshot) {
        if (!snapshot.hasData) {
            return Center(child: CircularProgressIndicator());
         } else {
            return ListView.builder(
              itemCount: snapshot.data?.length,
              itemBuilder: (context, i) {

           return ListTile( 
           title: Text(snapshot.data[i].longitude), 
           subtitle: Text(snapshot.data[i].latitude), 
           );                                          
         }
     }
)
  • Related