Bad state: cannot get a field on a DocumentSnapshotPlatform which does not exist

Mateusz Sylwester Sołtys

I'm new to Flutter. I made future to create new user document if it doesn't exist in "users collection firebase cloud". But the problem is, that I need to read that doc in next step (I want to know, that user is admin or no).

I get this error like that if I need to create a new document:

StateError (Bad state: cannot get a field on a DocumentSnapshotPlatform which does not exist)

This is my create doc future:

Future<void> createUserDocIfDontExist(String id) async {
    const bool userAdmin = false;
    const int userPoints = 0;
    FirebaseFirestore.instance
        .collection('users')
        .doc(id)
        .get()
        .then((docSnaoshot) => {
              if (!docSnaoshot.exists)
                docSnaoshot.reference
                    .set({'admin': userAdmin, 'points': userPoints})
            });
  }

This is my read doc future:

Future<GlobalDataModel> getAdminInfo(String id) async {
    final admin =
        await FirebaseFirestore.instance.collection('users').doc(id).get();
    return model.copyWith(admin: admin['admin']);
  }

This is my create document cubit:

Future<void> checkOrCreateUserDoc() async {
    final GlobalDataModel user = await _globalRemoteDataSource.getUserID();
    return _globalRemoteDataSource.createUserDocIfDontExist(user.user!);
  }

This is my read document cubit:

Future<void> initGlobalAdmin() async {
    final GlobalDataModel user = await _globalRemoteDataSource.getUserID();
    final GlobalDataModel admin =
        await _globalRemoteDataSource.getAdminInfo(user.user!);
    emit(state.copyWith(admin: admin.admin));
  }

And the place in the code where I use them:

 Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => HomePageCubit(),
      child: BlocBuilder<HomePageCubit, HomePageState>(
        builder: (context, home) {
          int currentIndex = home.currentIndex;
          final screens = [OfferPage(), CollectPage(), ProfilePage()];
          return BlocBuilder<RootCubit, RootState>(
            builder: (context, root) {
              context.read<RootCubit>().checkOrCreateUserDoc();
              context.read<RootCubit>().initGlobalAdmin();
              context.read<RootCubit>().initGlobalSteram();
              if (root.admin == null) {
                const LoadingPage();
              }
              return Scaffold(

Everything works fine if the user document already exists. The problem only occurs right after creating a new document.

Jilmar Xa

Your createUserDocIfDontExist method is async but you need to wait the future completes before continue.

Future<void> createUserDocIfDontExist(String id) async {
  final firestore = FirebaseFirestore.instance;
  const bool userAdmin = false;
  const int userPoints = 0;

  final userDoc = await firestore.collection('users').doc(id).get();

  if (!userDoc.exists) {
    await firestore
        .collection('users')
        .doc(id)
        .set({'admin': userAdmin, 'points': userPoints});
  }
}

Also you have future dependency so can't invoke methods separately like you do in the BlocBuilder'builder. Change to..

   return BlocBuilder<RootCubit, RootState>(
            builder: (context, root) {
              context.read<RootCubit>().checkOrCreateUserDoc();
              context.read<RootCubit>().initGlobalSteram();
              if (root.admin == null) {
                const LoadingPage();
              }

That method should be

Future<void> checkOrCreateUserDoc() async {
  final GlobalDataModel user = await _globalRemoteDataSource.getUserID();
  await _globalRemoteDataSource.createUserDocIfDontExist(user.user!);
  await initGlobalAdmin();
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Bad state: cannot get a field on a DocumentSnapshotPlatform which does not exist, Firebase Flutter

How can I resolve " Bad state: cannot get a field on a DocumentSnapshotPlatform which does not exist"

Exception: Bad state: cannot get a field on a DocumentSnapshotPlatform which does not exist provider

Flutter: Unhandled Exception: Bad state: field does not exist within the DocumentSnapshotPlatform

Problem with stream and firebase Bad state: field does not exist within the DocumentSnapshotPlatform

StateError (Bad state: field does not exist within the DocumentSnapshotPlatform) on flutter

Error: Bad state : field does not exist within the DocumentSnapshotPlatform

Bad state: field does not exist within the DocumentSnapshotPlatform error

flutter Bad state: field does not exist within the DocumentSnapshotPlatform

Flutter: Bad state: field does not exist within the DocumentSnapshotPlatform in streambuilder

Flutter - "Bad state: field does not exist within the DocumentSnapShotPlatform"

StateError (Bad state: field does not exist within the DocumentSnapshotPlatform). How can I get a doc from firestore?

I tried to display 'DateTime' on flutter UI get from firestore but show " Bad state: field does not exist within the DocumentSnapshotPlatform "

Bad state: field does not exist within the DocumentSnapshotPlatform flutter error even though field exists

How to fix Bad state: field does not exist within the DocumentSnapshotPlatform Firebase Flutter FutureBuilder

Bad state: field does not exist within the DocumentSnapshotPlatform. Giving this error but don't know where the error is

field dos not exist within the DocumentSnapshotPlatform

Django: Get objects for which ForeignKey does not exist

The association refers to the inverse side field which does not exist

ant fileset cannot find directory which does exist

Using Django/Postgres get a calculated field which get a field value if exist if not another field value

Field does not exist ODOO

How to get all result if unwind field does not exist in mongodb

Get-ChildItem Cannot Find Path Because It Does Not Exist

Foreign keys which does not exist

Minishift - cannot start - Error starting the VM: Error getting the state for host: machine does not exist

Why does this error exist: "Invariant Violation: Cannot update during an existing state transition"

If field does not exist, query by a different field

How do I access React State properties using TypeScript? Get property does not exist on type error

TOP Ranking

HotTag

Archive