Search code examples
flutterdartgoogle-cloud-firestorestream-builder

Failed assertion: boolean expression must not be null (for documentsnapshot data)


When I run the code below, I get the error message as shown below:

======== Exception caught by widgets library ======================================================= The following assertion was thrown building StreamBuilder(dirty, state: _StreamBuilderBaseState<DocumentSnapshot, AsyncSnapshot>#cfcf8): Failed assertion: boolean expression must not be null

The code I ran is as shown below:

class DataState extends AppState {
  final CollectionReference dataCollection =
  FirebaseFirestore.instance.collection('data');

  Stream<DocumentSnapshot> dataStream({String uid}) =>
      dataCollection.doc(uid).snapshots();

class WaitingPage extends StatefulWidget {
  @override
  _WaitingPageState createState() => _WaitingPageState();
}

class _WaitingPageState extends State<WaitingPage> {
  @override
  Widget build(BuildContext context) {
    final AuthState userProvider = Provider.of<AuthState>(context);
    var dataState = Provider.of<DataState>(context, listen:false);
    return (userProvider.userModel != null)
        ? StreamBuilder<DocumentSnapshot>(
      stream: dataState.dataStream(uid: userProvider.userModel.userId),
      builder: (context, snapshot) {
        if (snapshot.hasData && snapshot.data.data() != null) {
          Data data = Data.fromMap(snapshot.data.data());
          if (data.hasPickup) {
            return DataPage(data:data);
          }
          else{
            return Scaffold(
              body: Container(
              ),
            );
          }
        }
        return Scaffold(
          body: Center(
            child: CircularProgressIndicator(),
          ),
        );
      },
    )
        : Scaffold(
      body: Center(
        child: CircularProgressIndicator(),
      ),
    );
  }
}

Any suggestion on how to change the code to make it work? Thank you :)


Solution

  • The value of data.hasPickup is probably being null for some value and this is causing this error, in order to fix this treat "symptom" you should make a if (data.hasPickup != null) check in your builder and this will be mitigated.

    That being said, the actual root cause of the issue is not in here, but when you create these documents, a best practice for avoiding this kind of issue is to never initialize Firestore value with a null value (or at least value that will be actively using), and instead use a default value such as false.