flutterfirebasedartgoogle-cloud-firestorenetworkimageview

Null check operator used on a null value waiting for the network image to load


when i sign in with a firebase user i want his profile picture to show in the home page drawer from the firestore url field, so and show in a circle avatar widget, so i wrote a function to get the url as a string and provide it to the Network image(),

String? stringUrl;

  Future<String?> getData() async{
    var url = await FirebaseFirestore.instance
        .collection('users')
        .doc(currentUserUid)
        .get();
    setState(() {
      stringUrl= url['photourl'];
    });
    return null;
  }

then i provide this String url to the network image in the circle avatar widget

UserAccountsDrawerHeader(
              accountName: _getFieldDataToText(context, fieldName: 'name', currentUserUid: currentUserUid) ,
              accountEmail: _getFieldDataToText(context, fieldName: 'email', currentUserUid: currentUserUid) ,
              currentAccountPicture: CircleAvatar(
                backgroundImage: NetworkImage(stringUrl!),
              ),
            ),

but when i run my app and write my user and pw to login, just after loging in i get a red screen with this error "Null check operator used on a null value" for a second and it disappears and the app continue to work normally.

i think it's because the image is not yet reloaded so i get a null value ? i don't know whats the problem and i can't figure it out , can you help me?

i checked every async and await in the code and there is no errors.


Solution

  • When you put a ! after a nullable variable you are saying "I know for certain this value is not null right now". When Flutter finds this on a value that in fact is null, it raises the error you get.

    Indeed, your stringUrl variable will be null while the data is being loaded from the database. During that time you probably don't want to show any image in the UI, so you could for example handle it like this:

    currentAccountPicture: stringUrl != null
      ? CircleAvatar(backgroundImage: NetworkImage(stringUrl!)),
      : CircularProgressIndicator(),