简体   繁体   中英

Flutter not updating firebase collection

as per the question I can't seem to get my flutter app to update my firebase collection when I get a user to sign up. I get no error messages or any warnings, only thing I can think of is if something is null and therefore not updating but I can't see how since my authentication works and I can see the user in firebase authentication tab.

I've checked my rules and it looks okay

在此处输入图像描述

My code is as follows:

///sign up function
  Future<String?> signUp(
      {required String email, required String password}) async {
    try {
      await _firebaseAuth.createUserWithEmailAndPassword(
          email: email, password: password);

      var currentUser = FirebaseAuth.instance.currentUser;
      FirebaseFirestore.instance.collection('USER_TABLE').doc().update({
        'email': currentUser!.email,
        'firstName': 'Joe',
        'lastName': 'bloggs',
        'userID': currentUser.uid,
      });

      return "Signed up";
    } on FirebaseAuthException catch (e) {
      return e.message;
    }

my database looks as follows: 在此处输入图像描述

Thanks in advanced!

EDIT

Main.dart code

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        Provider<AuthenticationService>(
          create: (_) => AuthenticationService(FirebaseAuth.instance),
        ),
        StreamProvider(
          create: (context) =>
              context.read<AuthenticationService>().authStateChanges,
          initialData: null,
        )
      ],
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
          visualDensity: VisualDensity.adaptivePlatformDensity,
        ),
        home: AuthenticationWrapper(),
      ),
    );
  }
}

class AuthenticationWrapper extends StatelessWidget {
  const AuthenticationWrapper({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final firebaseUser = context.watch<User>();

    if (firebaseUser == null) {
      print('User is NOT signed in!');
      return const WelcomeScreen();
    }
    print('User is signed in!');
    return const MainScreen();

  }
}

This won't work:

FirebaseFirestore.instance.collection('USER_TABLE').doc().update({
  'email': currentUser!.email,
  'firstName': 'Joe',
  'lastName': 'bloggs',
  'userID': currentUser.uid,
});

From the reference docs for doc() :

If no path is provided, an auto-generated ID is used.

So your doc() call (without an ID) generates a new unique ID, and return a DocumentReference to that new, non-existing document. The problem after that though is that update() can only update existing documents, it never creates a document.


Since it seems that you don't know whether a document for the user exists, you should:

  1. Pass the UID in doc() as @THEODORE answered

    FirebaseFirestore.instance.collection('USER_TABLE').doc(currentUser.uid)
  2. Call set instead of update.

     FirebaseFirestore.instance.collection('USER_TABLE').doc(currentUser.uid).set({...})

    If the document may already exist, and you want to merge the new values with any existing values, you can pass SetOptions to set for that.

     FirebaseFirestore.instance.collection('USER_TABLE').doc(currentUser.uid).set({...}, SetOptions(merge: true))

I see the issue "update method needs an ID" only "add method doesn't "

  FirebaseFirestore.instance.collection('USER_TABLE').doc(currentUser.uid).update({
    'email': currentUser!.email,
    'firstName': 'Joe',
    'lastName': 'bloggs',
    'userID': currentUser.uid,
  });

or

  FirebaseFirestore.instance.collection('USER_TABLE').add({
    'email': currentUser!.email,
    'firstName': 'Joe',
    'lastName': 'bloggs',
    'userID': currentUser.uid,
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM