Home > other >  Flutter - type '() => Map<String, dynamic>?' is not a subtype of type 'Map&l
Flutter - type '() => Map<String, dynamic>?' is not a subtype of type 'Map&l

Time:04-29

I'm trying to get the current user's data from firestore and return them back in a user model but I'm getting this exception. Does anyone know how to fix this?

Exception

import 'package:ayu_app/utils/strings.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:ayu_app/models/user.dart' as u;

class FirebaseMethods {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  static final FirebaseFirestore firestore = FirebaseFirestore.instance;

  static final CollectionReference _userCollection =
      _firestore.collection(USERS_COLLECTION);

  static final FirebaseFirestore _firestore = FirebaseFirestore.instance;

  //user class
  late u.User user;

  Future<User> getCurrentUser() async {
    User currentUser;
    currentUser = _auth.currentUser!;
    return currentUser;
  }

  Future<u.User> getUserDetails() async {
    User currentUser = await getCurrentUser();

    DocumentSnapshot documentSnapshot =
        await _userCollection.doc(currentUser.uid).get();

    Map<String, dynamic> data = documentSnapshot.data as Map<String, dynamic>;

    return u.User.fromJson(data);
  }
}

CodePudding user response:

You need to change like below.

[Before]

Map<String, dynamic> data = documentSnapshot.data as Map<String, dynamic>;

[After]

Map<String, dynamic> data = documentSnapshot.data!.data() as Map<String, dynamic><br>

CodePudding user response:

snapshot.data is nullable so it can't cast it to non-nullable type. Use some null-checking expressions if you want to have non-nullable Map

// it will instantiate with <String, dynamic>{} (empty Map) if data is null 
Map<String, dynamic> data = dataSnapshot.data ?? {};

Or declare it as nullable Map like:

Map<String, dynamic>? data = dataSnapshot.data;
  • Related