How do you save user data to firestore database?

When using the iOS simulator to run my app when i register users their email and uid gets saved to the auth. But the users data does not get saved to the firestore database to create a collection.

This happens with both my register data and my user post data.

The problem is I can see in my firebase console in authentication tab that many new users getting authenticated but users data isn’t being stored in firestore.

    import 'package:flutter/material.dart';
import 'package:campusu/components/rounded_button.dart';
import 'package:campusu/screens/login_screen.dart';
import 'package:campusu/utilities/constants.dart';
import 'package:campusu/services/auth.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';

class NewRegistrationScreen extends StatefulWidget {
  const NewRegistrationScreen({super.key});

  static String id = 'new_registration_screen';

  @override
  State<NewRegistrationScreen> createState() => _NewRegistrationScreenState();
}

class _NewRegistrationScreenState extends State<NewRegistrationScreen> {
  final Auth _authService = Auth();
  bool showSpinner = false;
  late String email;
  late String password;
  late String userFullName;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: ModalProgressHUD(
        inAsyncCall: showSpinner,
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 24.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              Flexible(
                child: Hero(
                  tag: 'logo',
                  child: SizedBox(
                    height: 200.0,
                    child: Image.asset('images/logo.png'),
                  ),
                ),
              ),
              const SizedBox(height: 0.0),
              TextField(
                keyboardType: TextInputType.emailAddress,
                textAlign: TextAlign.center,
                onChanged: (value) {
                  userFullName = value;
                },
                decoration: kTextFieldDecoration.copyWith(
                    hintText: 'Enter your full name.'),
              ),
              const SizedBox(height: 8.0),
              TextField(
                keyboardType: TextInputType.emailAddress,
                textAlign: TextAlign.center,
                onChanged: (value) {
                  email = value;
                },
                decoration: kTextFieldDecoration.copyWith(
                    hintText: 'Enter your email.'),
              ),
              const SizedBox(height: 8.0),
              TextField(
                obscureText: true,
                textAlign: TextAlign.center,
                onChanged: (value) {
                  password = value;
                },
                decoration: kTextFieldDecoration.copyWith(
                    hintText: 'Enter your password.'),
              ),
              const SizedBox(height: 24.0),
              RoundedButton(
                onPressed: () async {
                  setState(() {
                    showSpinner = true;
                  });
                  try {
                    print('Attempting to register user');
                    await _authService.registerUser(
                      email: email,
                      password: password,
                      fullName: userFullName,
                    );
                    print('User registered successfully');

                    Navigator.pushNamed(context, LoginScreen.id);

                    setState(() {
                      showSpinner = false;
                    });
                  } catch (e) {
                    print('Error during registration: $e');
                    setState(() {
                      showSpinner = false;
                    });
                  }
                },
                color: kPrimaryColor,
                buttonText: 'Register',
              ),
              kDivider,
              const Text(
                textAlign: TextAlign.center,
                "Already registered?",
                style: TextStyle(
                  fontWeight: FontWeight.w700,
                  fontSize: 20.0,
                ),
              ),
              InkWell(
                onTap: () {
                  Navigator.pushNamed(context, LoginScreen.id);
                },
                child: const Text(
                  textAlign: TextAlign.center,
                  'Login',
                  style: kHyperlinkTextStyle,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

    import 'dart:io';
import 'package:campusu/components/custom_scaffold.dart';
import 'package:campusu/components/menu_bars.dart';
import 'package:campusu/components/rounded_button.dart';
import 'package:campusu/screens/login_screen.dart';
import 'package:campusu/utilities/constants.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:uuid/uuid.dart';

class CreatePost extends StatefulWidget {
  const CreatePost({super.key});

  static const String id = "create_post";

  @override
  State<CreatePost> createState() => _CreatePostState();
}

class _CreatePostState extends State<CreatePost> {
  final TextEditingController _contentTextController = TextEditingController();
  final TextEditingController _linkTextController = TextEditingController();
  final FocusNode _contentFocusNode = FocusNode();
  final _firestore = FirebaseFirestore.instance;
  final ImagePicker picker = ImagePicker();
  final _auth = FirebaseAuth.instance;
  final uuid = Uuid();

  File? _image;
  String _content = "";
  String _link = "";
  late final User? loggedInUser;

  Future pickImage() async {
    try {
      final XFile? image = await picker.pickImage(source: ImageSource.gallery);
      if (image == null) return;
      final imageTemp = File(image.path);
      setState(() => _image = imageTemp);
    } catch (e) {
      print('Failed to pick image: $e');
    }
  }

  Future<void> savePost({
    required String content,
    required File? image,
    required String userID,
    required String schoolID,
    required String clubID,
    String? link,
  }) async {
    final storageRef = FirebaseStorage.instance.ref();
    final uniqueID = uuid.v1();
    final postImageRef = storageRef.child("uploads/posts/$uniqueID");

    try {
      final user = _auth.currentUser;
      if (user == null) {
        print('User not authenticated.');
        return;
      }

      String imageUrl = "";
      if (image != null) {
        await postImageRef.putFile(image);
        imageUrl = await postImageRef.getDownloadURL();
        print('Image uploaded successfully: $imageUrl');
      }

      final postData = <String, dynamic>{
        'active': true,
        'club': clubID,
        'content': content,
        'created_at': Timestamp.now(),
        'image': imageUrl,
        'school': schoolID,
        'user': userID,
        'link': link,
      };

      await _firestore.collection('posts').add(postData);
      print('Post saved successfully: $postData');
    } catch (e) {
      print('Error saving post: $e');
    }
  }

  @override
  void initState() {
    loggedInUser = _auth.currentUser;
    super.initState();
  }

  Future<dynamic> _fetchUserMetadata() async {
    final user = _auth.currentUser;
    if (user == null) {
      Navigator.pushNamed(context, LoginScreen.id);
      return null;
    } else {
      try {
        print('Fetching user metadata for user_id: ${user.uid}');
        DocumentSnapshot userMetadataSnapshot = await _firestore
            .collection('usermetadata')
            .doc(user.uid)
            .get();

        if (userMetadataSnapshot.exists) {
          dynamic userData = userMetadataSnapshot.data();
          print('User metadata found: $userData');
          return userData;
        } else {
          print('User metadata document not found for user_id: ${user.uid}');
          return null;
        }
      } catch (e) {
        print('Error fetching user metadata: $e');
        return null;
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return CustomScaffold(
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            const SizedBox(height: 20.0),
            TextField(
              controller: _contentTextController,
              focusNode: _contentFocusNode,
              decoration: kTextFieldDecoration.copyWith(
                hintText: "Write your post content here...",
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(10.0),
                ),
                contentPadding: const EdgeInsets.all(20.0),
              ),
              style: const TextStyle(
                fontSize: 18.0,
                fontWeight: FontWeight.w400,
              ),
              maxLines: 5,
              onChanged: (value) {
                setState(() {
                  _content = value;
                });
              },
            ),
            const SizedBox(height: 20.0),
            TextField(
              controller: _linkTextController,
              decoration: kTextFieldDecoration.copyWith(
                hintText: "Add a link (optional)",
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(10.0),
                ),
                contentPadding: const EdgeInsets.all(20.0),
              ),
              style: const TextStyle(
                fontSize: 18.0,
                fontWeight: FontWeight.w400,
              ),
              onChanged: (value) {
                setState(() {
                  _link = value;
                });
              },
            ),
            const SizedBox(height: 20.0),
            if (_image != null)
              ClipRRect(
                borderRadius: BorderRadius.circular(10.0),
                child: Image.file(
                  _image!,
                  height: 200.0,
                  width: double.infinity,
                  fit: BoxFit.cover,
                ),
              ),
            const SizedBox(height: 10.0),
            TextButton.icon(
              onPressed: () async {
                await pickImage();
              },
              icon: const Icon(Icons.photo_library),
              label: const Text("Add Photo"),
              style: TextButton.styleFrom(
                foregroundColor: kPrimaryColor,
              ),
            ),
            const SizedBox(height: 20.0),
            RoundedButton(
              onPressed: () async {
                if (loggedInUser != null) {
                  final userMetadata = await _fetchUserMetadata();
                  if (userMetadata != null) {
                    final userSchool = userMetadata['school'] ?? "";
                    final userClub = userMetadata['club'] ?? "";

                    if (_content.isNotEmpty) {
                      await savePost(
                        content: _content,
                        image: _image,
                        userID: loggedInUser!.uid,
                        schoolID: userSchool,
                        clubID: userClub,
                        link: _link.isNotEmpty ? _link : null,
                      );
                      Navigator.pop(context);
                    } else {
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(content: Text('Post content cannot be empty.')),
                      );
                    }
                  } else {
                    print('User metadata is null for user_id: ${loggedInUser!.uid}');
                  }
                } else {
                  print('Logged in user is null.');
                }
              },
              color: kPrimaryColor,
              buttonText: 'Post',
            ),
          ],
        ),
      ),
      bottomNavigationBar: const BottomMenuBar(),
    );
  }
}

My database rules give users the option to read and write but still no data is being added to the firestore.

    rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // Rule for user profiles
    match /users/{userId} {
      allow read, write: if request.auth != null && request.auth.uid == userId;
    }

    // Rule for posts
    match /posts/{postId} {
      allow read, write: if request.auth != null;
    }

    // Rule for user metadata
    match /usermetadata/{userId} {
      allow read, write: if request.auth != null && request.auth.uid == userId;
    }

    // Rule for basicCollection
    match /basicCollection/{documentId} {
      allow read, write: if request.auth != null;
    }
  }
}

New contributor

Mohamed Coulibaly is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật