Home > Software engineering >  Firebase Firestore set() method not working on Flutter
Firebase Firestore set() method not working on Flutter

Time:01-16

When I try to use the set method to add a new document to my firestore database, nothing happens.

Future<void> _createUser() async {
    try {
      await Auth().createUserWithEmailAndPassowrd(
        email: _emailController.text,
        password: _passwordController.text,
      );

      final newUser = UserData(
        name: '',
        dateOfBirth: DateTime.now(),
        sex: false,
        location: GeoPoint(0, 0),
        bio: '',
        sportsPlayed: Map(),
        hasSetupAccount: false,
        // profileImage: null,
      );

      final json = newUser.toJson();
      FirebaseFirestore.instance
          .collection('Users')
          .doc(Auth().currentUser!.uid.toString())
          .set(json);

CodePudding user response:

The set(json) call returns a Future and if the call fails, that future is rejected. But your code currently doesn't handle that.

The simplest way to detect such errors is to use await, similar to what you already do for createUserWithEmailAndPassowrd [sic].

await FirebaseFirestore.instance
      .collection('Users')
      .doc(Auth().currentUser!.uid.toString())
      .set(json);

Using await translates the failing Future into an exception that your existing catch block can then handle and display to discover the root cause of the problem.

  • Related