简体   繁体   中英

Flutter error: The property 'docs' can't be unconditionally accessed because the receiver can be 'null'

I am struggling to resolve these two errors.

error: The property 'docs' can't be unconditionally accessed because the receiver can be 'null'. (unchecked_use_of_nullable_value at [church_app] lib\Screens\DevotionalList.dart:23)

error: The parameter 'devotional' can't have a value of 'null' because of its type, but the implicit default value is 'null'. (missing_default_value_for_parameter at [church_app] lib\Screens\DevotionalList.dart:39)

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';

class DevotionalList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: FirebaseFirestore.instance.collection('devotionals').snapshots(),
      builder: (context, snapshot) {
        if (snapshot.hasError) {
          return Center(
            child: Text('Error: ${snapshot.error}'),
          );
        }

        if (!snapshot.hasData) {
          return Center(
            child: CircularProgressIndicator(),
          );
        }

        // Use the .docs property to access the list of documents.
        List<DocumentSnapshot> documents = snapshot.data.docs;
        return ListView.builder(
          itemCount: documents.length,
          itemBuilder: (context, index) {
            DocumentSnapshot devotional = documents[index];
            return DevotionalTile(devotional: devotional);
          },
        );
      },
    );
  }
}

class DevotionalTile extends StatelessWidget {
  final DocumentSnapshot devotional;

  DevotionalTile({this.devotional});

  @override
  Widget build(BuildContext context) {
    if (devotional == null) {
      return Container();
    }

    return ExpansionTile(
      title: Text(devotional['title']),
      subtitle: Text('By ${devotional['author']}'),
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Text(devotional['body']),
        ),
      ],
    );
  }
}

Any assistance would be appreciated.

Tried adding null exceptions but I still run into the same error.

at the point when your call snapshot.data.docs , it can't be null since you checked first with the hasError , so you can tell this to Dart by explicitly adding a ! , instead of this:

List<DocumentSnapshot> documents = snapshot.data.docs;

add ! , so it will be this:

List<DocumentSnapshot> documents = snapshot.data.docs!;

this will fix both the error you're facing.

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