简体   繁体   中英

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:

在此处输入图像描述

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我的颤振医生

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']),

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM