AmirTheFree
AmirTheFree

Reputation: 66

NoSuchMethodError: The method '[]' was called on null - Flutter

I want to read data from this JSON in this way (PLEASE READ CODE COMMENTS):

class Profile extends StatefulWidget {
  final id;

  Profile({Key? key, @required this.id}) : super(key: key);

  @override
  _ProfileState createState() => _ProfileState();
}

class _ProfileState extends State<Profile> {
  var data;
  @override
  void initState() {
    super.initState();
    void getData() async {
      Response response = await get(
          Uri.parse('https://en.gravatar.com/' + widget.id + '.json'));
      this.data = json.decode(utf8.decode(response.bodyBytes));
      // READ PLEASE >>> Data successfully is loaded from server & if you 
      // print this.data it will show full data in console <<< READ PLEASE
    }

    getData();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Profile | MWX Gravatar Viewer',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Profile | MGV'),
        ),
        body: Center(
          child: Column(
            children: [
              Text(this.data['entry'][0]['name']['familyName']), // Where raises error
            ],
          ),
        ),
      ),
    );
  }
}

And i get this error while rendering page:

The following NoSuchMethodError was thrown building Profile(dirty, state: _ProfileState#35267):
The method '[]' was called on null.
Receiver: null
Tried calling: []("entry")

NOTE: After a hot reload error is gone & I CAN SEE THE DATA I NEEDED ON SCREEN but every time when I want to load the page this error will be shown although I can see what I expected, after a hot reload

Upvotes: 0

Views: 4733

Answers (2)

NelsonThiago
NelsonThiago

Reputation: 830

Your body might be running and not waiting for your getData() on initState. Try to check if it's null before using it:

body: Center(
          child: Column(
            children: [
              Text(this.data != null ? this.data['entry'][0]['name']['familyName'] : 'no data'), // Where raises error
            ],
          ),
        ),

Or use a FutureBuilder.

Upvotes: 2

Nik
Nik

Reputation: 2060

This is because you are calling network request and at same time you are using data which is null by default so you can use either FutureBuilder() or handle error by null check

Upvotes: 1

Related Questions