Search code examples
flutterdartdart-null-safety

Streambuilder - error after flutter migration - snapshot syntax


I used this code bevor migration

StreamBuilder(
          stream: FirebaseDatabase.instance
              .ref()
              .child('user')
              .child(_userID)
              .onValue,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              _networkImageUrl = snapshot.data.snapshot.value["img"];
              return Text(_networkImageUrl.toString());
             } else {
               return Container();
            }
          }),

after "dart pub upgrade --null-safety" I get the error:

The property 'snapshot' can't be unconditionally accessed because the receiver can be 'null'.

I tried to fix it with "!" but it doesn't work, it keeps the same error


Solution

  • this is the code:

    StreamBuilder<DatabaseEvent>(
              stream: FirebaseDatabase.instance
                  .ref()
                  .child('user')
                  .child(_userID)
                  .onValue,
              builder: (BuildContext context,AsyncSnapshot snapshot) {
                if (snapshot.hasData) {
                  Map<dynamic, dynamic> userDocument = snapshot.data.snapshot.value;
                  _networkImageUrl = userDocument["img"]
                  return Text(_networkImageUrl.toString());
                 } else {
                   return Container();
                }
              }),
    

    Thanks to @h8moss