skip to Main Content

I am trying to retrieve user data using a DocumentSnapshot. However I am getting a casterror because the instance that I created is pointing to null. So I tried calling the method getUserProfileData in the initState method to see if it could assign a value to my DocumentSnapshot instance but I still get that error. Please may anyone kindly help.

//DocumentSnapshot instance that is null
DocumentSnapshot? userDocument;

  getUserProfileData() {
    FirebaseFirestore.instance
        .collection('users')
        .doc(FirebaseAuth.instance.currentUser!.uid)
        .snapshots()
        .listen((event) {
      userDocument = event;
    });
  }

 @override
  void initState() {
    getUserProfileData();
//This is where the castError occurs because userDocument is null
    nameController.text = userDocument!.get('name');
    userNameController.text = userDocument!.get('username');

    try {
      descriptionController.text = userDocument!.get('description');
    } catch (e) {
      descriptionController.text = '';
    }

    try {
      followers = userDocument!.get('followers').length;
    } catch (e) {
      followers = 0;
    }

    try {
      following = userDocument!.get('following').length;
    } catch (e) {
      following = 0;
    }
  }

2

Answers


  1. It would be better to use StreamBuilder for firstore-snapshot.

      late final stream = FirebaseFirestore.instance
          .collection('users')
          .doc(FirebaseAuth.instance.currentUser!.uid)
          .snapshots();
    
      @override
      Widget build(BuildContext context) {
        return StreamBuilder(
          stream: stream,
          builder: (context, snapshot) {....},
        );
      }
    

    Also error can be bypass like

      getUserProfileData() {
        FirebaseFirestore.instance
            .collection('users')
            .doc(FirebaseAuth.instance.currentUser!.uid)
            .snapshots()
            .listen((event) {
          userDocument = event;
          /// all those stuff here
            nameController.text = userDocument!.get('name');
            userNameController.text = userDocument!.get('username');
                   ..........
    
    Login or Signup to reply.
  2. Try use async/await for getUserProfileData() function

    getUserProfileData() async {
        await FirebaseFirestore.instance
            .collection('users')
            .doc(FirebaseAuth.instance.currentUser!.uid)
            .snapshots()
            .listen((event) {
          userDocument = event;
        });
      }
    
    @override
      void initState() {
        getUserProfileData();
    
    // Replace with default value case userDocument is null
        nameController.text = userDocument!.get('name') ?? "";
        userNameController.text = userDocument!.get('username') ?? "";
    
        try {
          descriptionController.text = userDocument!.get('description') ?? "";
        } catch (e) {
          descriptionController.text = '';
        }
    
        try {
          followers = userDocument!.get('followers').length ?? 0;
        } catch (e) {
          followers = 0;
        }
    
        try {
          following = userDocument!.get('following').length ?? 0;
        } catch (e) {
          following = 0;
        }
      }
    

    Async determines that a method will be asynchronous, that is, it will not return something immediately, so the application can continue executing other tasks while processing is not finished.

    await serves to determine that the application must wait for a response from a function before continuing execution. This is very important because there are cases where a function depends on the return of another.

    a ?? b means that if the value of a is null, the value b will be assigned

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search