It’s been a few days now that I’m working on a flutter code by following tutorials to learn how to use Firebase with it. Nevertheless I completely block on a step that the person manages to realize, I have however copied the code at 100% and here is the error that I have:
The method 'data' can't be unconditionally invoked because the receiver can be 'null'. Try making the call conditional (using '?.') or adding a null check to the target ('!').
Here is the code:
class GetUserData extends StatelessWidget {
final String documentId;
final String fieldName;
final String fieldTitle;
GetUserData(
{super.key,
required this.documentId,
required this.fieldName,
required this.fieldTitle});
@override
Widget build(BuildContext context) {
CollectionReference users = firestore.collection('Users');
return FutureBuilder(
future: users.doc(documentId).get(),
builder:
(BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
Map<String, dynamic> data = snapshot.data.data();
return ListTile(
title: Text(data[fieldName]),
subtitle: Text(data[fieldTitle]),
);
});
}
}
I’ve tried many things:
Map<String, dynamic> data = snapshot.data!.data();
return FutureBuilder( future: users.doc(documentId).get(), builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) { Map<String, dynamic> data = snapshot.data!.data() as Map<String, dynamic>; return ListTile( title: Text(data[fieldName]), subtitle: Text(data[fieldTitle]), ); });
Here I don’t have the error but a crash when I debug with _CastError (Null check operator used on a null value)
I have looked everywhere and I don’t understand how to solve this,
Thank you so much for your help,
2
Answers
try to handle all condition
You are not decoding the response from the firebase properly, try considering the below code: