【问题标题】:the collection and values cannot show up in the Cloud Firestore in flutter集合和值无法显示在 Cloud Firestore 中
【发布时间】:2021-03-25 12:07:21
【问题描述】:

在我的 Flutter 应用中创建后,我无法在 Cloud Firestore 中看到这些集合和值。我正在使用 Flutter 和 Firebase 开发 Flutter 移动应用程序。我使用 Cloud Firestore 来保存数据。当我运行应用程序时,我可以从 VS Code 的终端看到“hi”,但是当我去 firebase 时,刷新 cloud firestore 页面,我看不到 cloud firestore 中的集合和值。我试图删除 firebase 项目并重新创建它。但它没有用。我尝试使用Collection("users").add(...).then(value){print(value.id);}。从终端,我可以看到 ID。但我仍然看不到 Cloud Firestore 中的集合和值。我不知道我的应用程序有什么问题。我需要帮助。

代码是:

   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": "example@example.com",
        "address": {"street": "street 24", "city": "new york"}
      }).then((value) {
        print('hi');
      });
    }

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

我在app下的build.gradle:

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'

android下的build.gradle:

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
}

安全规则是:

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

感谢您的帮助。

【问题讨论】:

  • 您的控制台中是否有 PERMISSION DENIED 消息?
  • 我没有权限被拒绝消息。但我在检查控制台中得到状态码 404

标签: android firebase flutter google-cloud-firestore


【解决方案1】:

我认为问题出在这个声明中

    await Firebase.initializeApp(); 

我认为您应该删除 await 那里和功能中的关键字,并且当您使用该功能在项目中初始化 Firebase 时,您需要将项目的凭据作为参数那个函数,这是你应该如何做的一个例子:

    // 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
});

如果这能解决问题,请告诉我

【讨论】:

    【解决方案2】:

    删除await 关键字。它与then 冲突。你需要使用或awaitthen

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

    【讨论】:

    • 我删除了 await 和 async 关键字。但问题依然存在。
    猜你喜欢
    • 2021-09-03
    • 2021-09-26
    • 1970-01-01
    • 2020-11-23
    • 2019-07-20
    • 2021-05-06
    • 2020-07-11
    • 2018-04-23
    • 2018-07-07
    相关资源
    最近更新 更多