【问题标题】:Writing to Firebase Realtime Database with Flutter使用 Flutter 写入 Firebase 实时数据库
【发布时间】:2021-07-03 13:18:34
【问题描述】:

我已经仔细阅读了论坛、谷歌和 youtube,以获取有关使用颤振将数据写入实时数据库的信息,但即使是最基本的写入,我也没有找到合适的指南。

话虽如此,在我的应用程序中,我目前正在尝试将用户的电子邮件作为用户新 ID 的子项保存到数据库中。我试图在调用 .createUserWithEmailAndPassword 后立即执行此操作。这一切都应该在点击材质按钮时发生。我之前在 then 语句中有 write ,但这给了我一个错误。

代码:

FirebaseAuth userAuth = FirebaseAuth.instance;

void saveEmailInDb(String userId, String email) {
  final userRef = FirebaseDatabase.instance.reference();
  userRef.child(userId).child("Email").push().set(email);
}

//inside of the build widget

MaterialButton(
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(32),
                      ),
                      color: colorPalette.chooseColor('yellow'),
                      child: Container(
                        padding: EdgeInsets.all(13),
                        child: Text(
                          'Register',
                          style: GoogleFonts.ubuntu(
                              color: colorPalette.chooseColor('darkGrey'),
                              fontSize: 17),
                        ),
                      ),
                      onPressed: () async {
                        try {
                          UserCredential userCredential = await userAuth
                              .createUserWithEmailAndPassword(
                                  email: tecEmail.text,
                                  password: tecPassword.text)
                              .then(
                                (value) => Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder: (context) => LoadingPage(),
                                  ),
                                ),
                              );
                          saveEmailInDb(
                              userCredential.user.uid, tecEmail.text);
                        } on FirebaseAuthException catch (e) {
                          if (e.code == 'weak-password') {
                            print('The password provided is too weak.');
                          } else if (e.code == 'email-already-in-use') {
                            print('The account already exists for that email.');
                          }
                        } catch (e) {
                          print(e);
                        }
                      },
                    ),

我已经在主窗口小部件中实例化了 firebase:

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(
    GetMaterialApp(
      home: LoadingPage(),
    ),
  );
}

现在,我知道 Flutter 已正确连接到我的应用程序,因为在身份验证的 Firebase 控制台中创建了一个帐户。但是,没有任何内容写入数据库,并且由于没有适当的指南或官方文档,我不确定如何继续。

数据库规则:

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

【问题讨论】:

  • 我建议不要谈论您的特定用例缺乏文档,而是分享您从调试代码中获得的更多信息。当您在调试器中单步执行代码时会发生什么?它有没有到达这条线userRef.child(userId).child("Email").push().set(email);userIdemail 是您期望的值吗?然后,当您越过那条线时,是否有任何内容写入您的应用程序的日志?如果没有,FirebaseDatabase.instance.reference().set("Hello") 是否写入数据库?
  • 顺便说一句,我不是你的问题的反对者,但可以想象这可能是发生这种情况的原因。
  • 我解决了它。因为导航调用发生在数据库写入之前,所以数据库写入从未发生。至于文档参考,我只是想让人们知道我在问这里之前搜索过。无论如何,与例如身份验证相比,它确实缺乏具体示例:firebase.flutter.dev/docs/database/overview
  • 如果您解决了问题,请考虑在下面发布答案,其中包含您对解决问题的上述代码所做的具体更改。

标签: firebase flutter firebase-realtime-database firebase-authentication


【解决方案1】:

答案:将导航代码移到 then 语句之外,并在数据库写入下方,足以解决这个问题。基本上,导航在调用数据库代码之前弹出小部件。修改后的代码如下:

                MaterialButton(
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(32),
                  ),
                  color: colorPalette.chooseColor('yellow'),
                  child: Container(
                    padding: EdgeInsets.all(13),
                    child: Text(
                      'Register',
                      style: GoogleFonts.ubuntu(
                          color: colorPalette.chooseColor('darkGrey'),
                          fontSize: 17),
                    ),
                  ),
                  onPressed: () async {
                    try {
                      UserCredential userCredential =
                          await userAuth.createUserWithEmailAndPassword(
                              email: tecEmail.text,
                              password: tecPassword.text);
                      saveEmailInDb(userCredential.user.uid, tecEmail.text);
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => LoadingPage(),
                        ),
                      );
                    } on FirebaseAuthException catch (e) {
                      if (e.code == 'weak-password') {
                        print('The password provided is too weak.');
                      } else if (e.code == 'email-already-in-use') {
                        print('The account already exists for that email.');
                      }
                    } catch (e) {
                      print(e);
                    }
                  },
                ),

【讨论】:

    猜你喜欢
    • 2020-09-13
    • 2021-10-13
    • 2020-05-30
    • 2019-10-11
    • 1970-01-01
    • 2022-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多