serdar aksoy
serdar aksoy

Reputation: 23

FutureBuilder The method '[]' was called on null. Receiver: null

Im getting this error in my dart code. If I delete coverImage widget , It gives error for other snapshat.data`s widget

My Error

Exception caught by widgets library The following NoSuchMethodError was thrown building FutureBuilder<DocumentSnapshot<Map<String, dynamic>>>(dirty, state: _FutureBuilderState<DocumentSnapshot<Map<String, dynamic>>>#45e11): The method '[]' was called on null. Receiver: null Tried calling:

enter image description here

The way Im using data.

image: DecorationImage(
                fit: BoxFit.cover,
                image: (snapshot.data['coverImage']).isEmpty
                    ? AssetImage('assets/background.png')
                    : NetworkImage(snapshot.data['coverImage']),
              ),

My flutter doctor My Flutter DOCTOR

Upvotes: 0

Views: 700

Answers (3)

sudhanshu shaurya
sudhanshu shaurya

Reputation: 235

check if ['coverImage'] is there in your database your error shows that this field is not in your database you can check in the code by

(snapshot.data['coverImage']).isEmpty || snapshot.data['coverImage'] ==null)

Upvotes: 0

croxx5f
croxx5f

Reputation: 5718

Hi in your switch statement you are not doing anything, so you are not filtering in which state the futurebuilder is and thus trying to access the data when its not already completed:

    return FutureBuilder(builder: ( context,  snapshot) {
      if(snapshot.hasData){
        return ListView();
        
      }else if (snapshot.hasError){
        return Center(child:Text(snapshot.error.toString()));
      }
      return Center(child: CircularProgressIndicator());



    }

Here the three principal states are taken care of.

Upvotes: 1

Ardi Rizmaldi
Ardi Rizmaldi

Reputation: 21

It's probably your snapshot data is null Maybe you should handle it with ? or == null

image: (snapshot?.data['coverImage']).isEmpty 

or

final dataCoverImage = snapshot.data['coverImage']

image: (dataCoverImage == null) || (dataCoverImage.isEmpty)
? AssetImage('assets/background.png')
: NetworkImage(snapshot.data['coverImage']),

Upvotes: 1

Related Questions