Sunny Sun
Sunny Sun

Reputation: 1

the collection and values cannot show up in the Cloud Firestore in flutter

I cannot see the collections and values in the Cloud Firestore after they were created in my Flutter app. I am working on a Flutter mobile app by using Flutter and Firebase. I use cloud firestore to keep data. when I run the app, I can see "hi" from VS Code's terminal, but when I went to the firebase, refresh the cloud firestore page, I can not see the collection and values in the cloud firestore. I tried to delete firebase project and recreate it. But it did not work. I tried to use Collection("users").add(...).then(value){print(value.id);}. From the terminal, I can see the ID. But I still cannot see the collection and values in the Cloud Firestore. I do not know what is wrong with my app. I need help.

The code is:

   import 'package:flutter/material.dart';
   import 'package:firebase_core/firebase_core.dart';
   import 'package:cloud_firestore/cloud_firestore.dart';

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

   class MyApp extends StatefulWidget {
     // This widget is the root of your application.
     override
     _createState() => _MyAppState();
   

   class _MyAppState extends State<MyApp> {
      @override
      Widget build(BuildContext context) {
        

        // firestore: a Firestore instance
        void _onPressed() async{
           await FirebaseFirestore.instance.collection("users").doc().set({
            "name": "john",
            "age": 50,
        "email": "[email protected]",
        "address": {"street": "street 24", "city": "new york"}
      }).then((value) {
        print('hi');
      });
    }

    return MaterialApp(
      home: Scaffold(
        body: Container(
          child: TextButton(
            onPressed: _onPressed,
            child: Text('Click'),
          ),
        ),
      ),
    );
  }
}

my build.gradle under app:

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion 30

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.skype_clone"
        minSdkVersion 19
        targetSdkVersion 30
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.google.firebase:firebase-firestore:21.4.2'
}
apply plugin: 'com.google.gms.google-services'

the build.gradle under android:

buildscript {
    ext.kotlin_version = '1.3.50'
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:4.1.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.5'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

the security rule is:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write;
    }
  }
}

I am appreciated for any help.

Upvotes: 0

Views: 1069

Answers (2)

Robertocd_98
Robertocd_98

Reputation: 404

I think that the problem is in this declaration

    await Firebase.initializeApp(); 

I think that you should remove the await keyword there and in the functcion, and when you use that function to initialize Firebase in the project you need to put the credential of the project as a parameter of that function, this is an example of how you should do it:

    // Initialize default app
    // Retrieve your own options values by adding a web app on
    // https://console.firebase.google.com
    firebase.initializeApp({
      apiKey: "AIza....",                             // Auth / General Use
      appId: "1:27992087142:web:ce....",              // General Use
      projectId: "my-firebase-project",               // General Use
      authDomain: "YOUR_APP.firebaseapp.com",         // Auth with popup/redirect
      databaseURL: "https://YOUR_APP.firebaseio.com", // Realtime Database
      storageBucket: "YOUR_APP.appspot.com",          // Storage
      messagingSenderId: "123456789",                 // Cloud Messaging
      measurementId: "G-12345"                        // Analytics
});

Please let me know if this solve the problem

Upvotes: 1

Simon Sot
Simon Sot

Reputation: 3136

delete await keyword. It conflicts with then. You need to use or await or then:

void _onPressed() async{
      FirebaseFirestore.instance.collection("users").doc().set({
        "name": "john",
        "age": 50,
        "email": "[email protected]",
        "address": {"street": "street 24", "city": "new york"}
      }).then((value) {
        print('hi');
      });
    }

Upvotes: 0

Related Questions