Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: Unhandled Exception: NoSuchMethodError: The getter 'id' was called on null. Receiver: null Tried calling: id

I'm having issues setting up signing up with an email and password using Flutter. I got it to sign the new user in and it saves their Firebase authentication info but it doesn't save any profile data to the Firebase Storage section. I'm not sure what I'm doing wrong here, I don't understand why id is null. Some help and guidance would be really appreciated!

This is the error I got

Unhandled Exception: NoSuchMethodError: The getter 'id' was called on null.
Receiver: null
Tried calling: id

This is from user.dart

import 'package:cloud_firestore/cloud_firestore.dart';

class User {
  final String id;
  final String profileName;
  final String username;
  final String photoUrl;
  final String url;
  final String email;
  final String bio;
  final String createdAt;

  User({
    this.id,
    this.profileName,
    this.username,
    this.photoUrl,
    this.url,
    this.email,
    this.bio,
    this.createdAt,
  });

  factory User.fromDocument(DocumentSnapshot doc) {
    return User(
      id: doc.documentID,
      email: doc['email'],
      username: doc['username'],
      photoUrl: doc['photoUrl'],
      url: doc['url'],
      profileName: doc['profileName'],
      bio: doc['bio'],
      createdAt: doc['createdAt'],
    );
  }
}

This is from Signup.dart

The error pointed to the usersReference.document line.

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:buddiesgram/models/user.dart';
import 'package:buddiesgram/pages/HomePage.dart';
import 'package:shared_preferences/shared_preferences.dart';


class SignupPage extends StatefulWidget {

  static final String id = 'signup_page';
  final DateTime timestamp = DateTime.now();
  User currentUser;

  @override
  _SignupPageState createState() => _SignupPageState();
}

class _SignupPageState extends State<SignupPage> {
  final  FirebaseAuth auth = FirebaseAuth.instance;
  final _formKey = GlobalKey<FormState>();
  String username, email, password;
  SharedPreferences preferences;

  checkIfSignedIn() async {
    auth.onAuthStateChanged.listen((user) {

      if (user != null) {
        Navigator.push(context, MaterialPageRoute(builder: (context) => HomePage()));
      }
    });

    @override
    void initState() {
      super.initState();
      this.checkIfSignedIn();
    }
  }

  saveUserInfoToFireStore() async {

    preferences = await SharedPreferences.getInstance();
    DocumentSnapshot documentSnapshot = await usersReference.document(currentUser.id).get();

    if(!documentSnapshot.exists) {
      usersReference.document(currentUser.id).setData({
        "id": currentUser.id,
        "profileName": currentUser.profileName,
        "username": currentUser.username,
        "photoUrl": currentUser.photoUrl,
        "email": currentUser.email,
        "bio": "",
        "timestamp": timestamp,
        "talkingTo": null,
      });

      //Write data to local
      //currentUser = currentUser as User;
      //await preferences.setString("id", currentUser.id);
      //await preferences.setString("profileName", currentUser.profileName);
      //await preferences.setString("photoUrl", currentUser.photoUrl);

      await followersReference.document(currentUser.id).collection("userFollowers").document(currentUser.id).setData({});

      documentSnapshot = await usersReference.document(currentUser.id).get();
    }

    currentUser = User.fromDocument(documentSnapshot);
  }

  signUp() async {
    if(_formKey.currentState.validate()) {
      _formKey.currentState.save();

      try{
        AuthResult authResult = await auth.createUserWithEmailAndPassword(email: email, password: password);
        FirebaseUser signedInUser = authResult.user;
        if(signedInUser != null) {
        saveUserInfoToFireStore();
        }
        Navigator.push(context, MaterialPageRoute(builder: (context) => HomePage()));
      }
      catch(e) {
        print(e);
      }
    }
  }

This is from Timeline.dart

The error pointed to both of the QuerySnapshot lines from those two methods.

retrieveTimeLine() async {
    QuerySnapshot querySnapshot = await timelineReference.document(currentUser.id)
        .collection("timelinePosts").orderBy("timestamp", descending: true).getDocuments();

    List<Post> allPosts = querySnapshot.documents.map((document) => Post.fromDocument(document)).toList();

    setState(() {
      this.posts = allPosts;
    });
  }

  retrieveFollowings() async {
    QuerySnapshot querySnapshot = await followingReference.document(currentUser.id)
        .collection("userFollowing").getDocuments();

    setState(() {
      followingsList = querySnapshot.documents.map((document) => document.documentID).toList();
    });
  }

Please let me know if I left anything out, that may help.

like image 574
Indigo Avatar asked Sep 17 '25 08:09

Indigo


2 Answers

currentUser is null because you didn't initialize the class. For example:

  saveUserInfoToFireStore() async {
    currentUser = User(); //initialize
    preferences = await SharedPreferences.getInstance();
    DocumentSnapshot documentSnapshot = await usersReference.document(currentUser.id).get();

Of course the above code still wont work, because id is equal to null. If the document id in your database is equal to the user uid, then do the following:

User loggedInUser;

  saveUserInfoToFireStore() async {
     var user = FirebaseAuth.instance.currentUser();
     loggedInUser = User(id : user.uid);
    preferences = await SharedPreferences.getInstance();
    DocumentSnapshot documentSnapshot = await usersReference.document(loggedInUser.id).get();

So here you get the uid of the user from Firebase Authentication and then since you are using optional named parameter, you can initialize the User class with the id property and use it inside the document() method.

like image 198
Peter Haddad Avatar answered Sep 18 '25 21:09

Peter Haddad


go to payment.dart and enable the option of the checkout page

enter image description here

and disable the native option

like image 25
Noman Riaz Avatar answered Sep 18 '25 21:09

Noman Riaz