skip to Main Content

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


  1. try to handle all condition

    @override
      Widget build(BuildContext context) {
        CollectionReference users = firestore.collection('Users');
        return FutureBuilder(
            future: users.doc(documentId).get(),
            builder:
                (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
               /// success fetch data
              if(snapshot.hasData){
               Map<String, dynamic> data = jsonDecode(snapshot.data);
               return ListTile(
                title: Text(data[fieldName]),
                subtitle: Text(data[fieldTitle]),
              );
              }
             /// failed and throw error
              else if(snapshot.hasError){
                return Text('${snapshot.error}');
              } 
            /// loading condition
            else {
            return Center(child:CircularProggressIndicator());
             }
            });
      }
    
    Login or Signup to reply.
  2. You are not decoding the response from the firebase properly, try considering the below code:

     @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
              child: FutureBuilder<DocumentSnapshot<Map<String, dynamic>>>(
            future: FirebaseFirestore.instance
                .collection('users')
                .doc(documentId) 
                .get(),
            builder: (_, snapshot) {
              if (snapshot.hasError) return Text('Error = ${snapshot.error}');
              if (snapshot.connectionState == ConnectionState.waiting) {
                return const Text("Loading");
              }
              Map<String, dynamic> data = snapshot.data!.data()!;
              return Text(data['fieldName']); // give your valid data here
            },
          )),
        );
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search