Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

firebase - How to implement null-safety in simple flutter-dart code with object snapshot.data?

I am new to flutter/dart coding, please help me solve the following:

Here is my code trying to fetch data from the FireStore collection "DinnerNames" but I get an analysis error on the snapshot.data object at the line:

itemCount: snapshot.data.documents.length

:

The problem:

An expression whose value can be 'null' must be null-checked before it can be dereferenced. Try checking that the value isn't 'null' before dereferencing it.

Here is the code sample generates the error:

CollectionReference dinners =
        FirebaseFirestore.instance.collection('DinnerNames');

    return Scaffold(
      appBar: AppBar(
        title: Text('My Dinner Voting App'),
      ),
      body: StreamBuilder(
          stream: dinners.snapshots(),
          builder: (context, snapshot){
            if (!snapshot.hasData) return const Text('Firestore snapshot is loading..');
            
            if (!snapshot.hasError)
              return const Text('Firestore snapshot has error..');
            
            if (snapshot.data == null){
              return const Text("Snapshot.data is null..");
            }else{
               return ListView.builder(
              itemExtent: 80.0,
              itemCount:  snapshot.data.documents.length,
              itemBuilder: (context, index) =>
                  _buildListItem(context, snapshot.data.documents[index]),
            ); 
            }           
          }
          ),
    );

here is the flutter version:

dave@DaveMacBook-Pro firebasetest % flutter --version
Flutter 1.25.0-8.2.pre ? channel beta ? https://github.com/flutter/flutter.git
Framework ? revision b0a2299859 (2 weeks ago) ? 2021-01-05 12:34:13 -0800
Engine ? revision 92ae191c17
Tools ? Dart 2.12.0 (build 2.12.0-133.2.beta)
question from:https://stackoverflow.com/questions/65844643/how-to-implement-null-safety-in-simple-flutter-dart-code-with-object-snapshot-da

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you're already checking:

snapshot.data == null

but it seems the analysis is indicating that documents can also be null, so try to include also:

if (snapshot.data.documents != null) { ... do what you need }

or try to change this code:

if (snapshot.data == null){
  return const Text("Snapshot.data is null..");
}

to this:

if (snapshot.data == null || snapshot.data.documents == null){
  return const Text("Snapshot.data is null..");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...