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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…