Home > Net >  Another exception was thrown: type '() => Map<String, dynamic>?' is not a subtype
Another exception was thrown: type '() => Map<String, dynamic>?' is not a subtype

Time:01-04

While returning Future builder am getting this error . . Another exception was thrown: type '() => Map<String, dynamic>?' is not a subtype of type 'Map<String, dynamic>' in type cast how do i resolve?? Thanks in advance.

                    return FutureBuilder(
                    future: FirebaseFirestore.instance
              .collection('Users').doc(userId).get(),
                    builder: (context, _snapshot) {
                      print("=======printing snapshot======");
                      print(_snapshot.hasData);
                      if (_snapshot.hasData) {
                        DocumentSnapshot docSnapUser =
                            _snapshot.data as DocumentSnapshot;
                        Map<String, dynamic> _user =
                            docSnapUser.data as Map<String, dynamic>;

CodePudding user response:

The error you are getting is related to null-safety. Basically you are assigning a value which can be null to a variable which must not be null; just typecasting will not help in this case. Try below:

 return FutureBuilder(
                future: FirebaseFirestore.instance
          .collection('Users').doc(userId).get(),
                builder: (context, _snapshot) {
                  if (_snapshot.hasData) {
                    DocumentSnapshot docSnapUser =
                        _snapshot.data as DocumentSnapshot;
                    Map<String, dynamic> _user =
                        docSnapUser?.data ?? Map<String, dynamic>(); // empty map if left is null

CodePudding user response:

data is a method, not a field.

docSnapUser.data as Map<String, dynamic>;

should be

docSnapUser.data();

CodePudding user response:

Look this one:

Another exception was thrown: type '() => Map<String, dynamic>?' is not a subtype of type 'Map<String, dynamic>'

Just handle your nullable exception like below:

Map<String, dynamic> _user = docSnapUser.data ?? Map<String, dynamic>();
  • Related