Flutter-如何在Firebase(实时DDB)中写入数据:权限被拒绝

时间:2018-09-06 19:07:08

标签: android firebase firebase-realtime-database dart flutter

我想在Firebase中写入数据,但出现权限错误,这是我尝试过的操作:

void initState() {
    super.initState();
    testFirebase();
 }

 Future testFirebase() async {

    initUser();

    //Initialize Firebase
    final FirebaseApp firebaseApp = await FirebaseApp.configure( ... );

    final FirebaseDatabase database = new FirebaseDatabase(app: firebaseApp);

    database.reference().child('counter').push().set(<String, String>{
      'var': 'test'
    });
  }

  Future initUser() async {
    googleUser = await _ensureLoggedInOnStartUp();
    if (googleUser == null) {
       setState(() {
         state.isLoading = false;
       });
    } else {
       var firebaseUser = await logIntoFirebase();
    }
  }

这是我的Firebase规则:

enter image description here

将google-services.json文件添加到应用的根目录:

enter image description here

结果:

我收到以下错误消息:

enter image description here

我也尝试过:

  

push()。setValue('2')

但是它不起作用,这让我发疯,我不明白...

有什么主意吗?

3 个答案:

答案 0 :(得分:2)

快速的初步检查是您需要await initUser()。所以:

Future testFirebase() async {

    await initUser();

    //Initialize Firebase
    final FirebaseApp firebaseApp = await FirebaseApp.configure( ... );

除非如此,否则我不希望在身份验证完成之前开始对数据库的调用。


更新:我刚刚验证了以下简单代码的确是这种情况:

void _signin() async {
  print("Calling __actuallySignin");
  __actuallySignin();
  print("called __actuallySignin and waited");
}
void __actuallySignin() async {
  print("Calling signIn...");
  await FirebaseAuth.instance.signInAnonymously();
  print("called signIn... and waited");
}

此打印:

flutter: Calling __actuallySignin
flutter: called __actuallySignin and waited
flutter: Calling signIn...
...
flutter: called signIn... and waited

因此__actuallySignin方法是在登录之前完成的。要使调用代码等待结果,请添加await

await __actuallySignin();

哪个输出:

flutter: Calling __actuallySignin
flutter: Calling signIn...
flutter: called signIn... and waited
flutter: called __actuallySignin and waited

答案 1 :(得分:1)

仅将await添加到initUser()无效,数据库也不正确。

解决方案:

FirebaseDatabase.instance.reference().child ...

而不是:

final FirebaseApp firebaseApp = await FirebaseApp.configure( ... );

final FirebaseDatabase database = new FirebaseDatabase(app: firebaseApp);

答案 2 :(得分:0)

我能够通过不使用插件文档中列出的方法访问数据库引用来解决此问题:

final FirebaseDatabase database = FirebaseDatabase(app: app);
this.databaseRef = database.reference();

但是要使用这种方法:

this.databaseRef = FirebaseDatabase.instance.reference();

使用多个Flutter文档时,您会发现有很多方法可以从实时数据库读取公共信息,但是只有一种方法可以读取依赖于auth变量的信息。这是我的经验。

工作方法:https://marcinszalek.pl/flutter/firebase-database-flutter-weighttracker/

非工作方法与插件文档相关:https://pub.dartlang.org/packages/firebase_database#-example-tab-

此外,我的项目是使用Firebase Flutter主文档配置的,用于将我的应用链接到Firebase:https://firebase.google.com/docs/flutter/setup