Flutter中Firebase Realtime Database无响应问题求助

原代码
import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_database/firebase_database.dart'; import 'package:flutter/material.dart'; import '../app settings/text sittings.dart'; import '../screens.dart'; // ignore: must_be_immutable class SignUpPage extends StatefulWidget { const SignUpPage({Key? key}) : super(key: key); @override State<SignUpPage> createState() => _SignUpPageState(); } class _SignUpPageState extends State<SignUpPage> { final namecontroller = TextEditingController(); final emailcontroller = TextEditingController(); final passwodconttroler = TextEditingController(); final conformpasswodconttroler = TextEditingController(); GlobalKey<FormState> formstate = GlobalKey<FormState>(); final database = FirebaseDatabase.instance; Future signUp() async { var formdata = formstate.currentState; if (formdata!.validate()) { formdata.save(); if (passwordconfirmed()) { try { final User? credential = (await FirebaseAuth.instance.createUserWithEmailAndPassword( email: emailcontroller.text, password: passwodconttroler.text, )) .user; return credential; } on FirebaseAuthException catch (e) { if (e.code == 'weak-password') { AwesomeDialog( context: context, dialogType: DialogType.warning, animType: AnimType.bottomSlide, title: 'Week Password', body: const Text( "The password is too weak", )).show(); } else if (e.code == 'email-already-in-use') { AwesomeDialog( context: context, dialogType: DialogType.warning, animType: AnimType.bottomSlide, title: 'Week Password', body: const Text( "The account already exists for that email", )).show(); } return null; } catch (e) { print(e); } } } if (signUp() != null) { DatabaseReference ref = FirebaseDatabase.instance.ref("name"); await ref.child("id").push().set({ "id": FirebaseAuth.instance.currentUser?.uid, "name": namecontroller.text, "email": emailcontroller.text, }); } } bool passwordconfirmed() { if (passwodconttroler.text.trim() == conformpasswodconttroler.text.trim()) { return true; } else { return false; } } void openSignScreen() { Navigator.of(context).pushReplacement( MaterialPageRoute(builder: (context) => const SignUpPage())); } @override void dispose() { super.dispose(); emailcontroller.dispose(); passwodconttroler.dispose(); conformpasswodconttroler.dispose(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white70, body: SafeArea( child: ListView(children: [ Stack( children: [ Form( key: formstate, child: Column( mainAxisAlignment: MainAxisAlignment.start, children: [ const SizedBox( height: 150, width: 60, ), const Text("Create Account", style: TextStyle( fontSize: 40, fontWeight: FontWeight.w800, fontFamily: 'Montserrat')), const SizedBox( height: 60, width: 20, ), Padding( padding: const EdgeInsets.only( left: 30, right: 30, bottom: 20), child: TextFormField( validator: (value) { if (value!.length > 20) { return "Password is very long"; } if (value.length < 7) { return "Password is very short"; } else { return null; } }, controller: namecontroller, keyboardType: TextInputType.visiblePassword, textAlignVertical: TextAlignVertical.bottom, decoration: InputDecoration( hintText: "Full Name", filled: true, fillColor: Colors.white12, border: OutlineInputBorder( borderRadius: BorderRadius.circular(45), borderSide: BorderSide.none), ), ), ), Padding( padding: const EdgeInsets.only( left: 30, right: 30, bottom: 20), child: TextFormField( validator: (value) { if (value!.length > 50) { return "Password is very long"; } if (value.length < 8) { return "Password is very short"; } else { return null; } }, controller: emailcontroller, keyboardType: TextInputType.emailAddress, textAlignVertical: TextAlignVertical.bottom, decoration: InputDecoration( hintText: "Email", filled: true, fillColor: Colors.white12, border: OutlineInputBorder( borderRadius: BorderRadius.circular(45), borderSide: BorderSide.none), ), ), ), Padding( padding: const EdgeInsets.only( left: 30, right: 30, bottom: 20), child: TextFormField( validator: (value) { if (value!.length > 20) { return "Password is very long"; } if (value.length < 7) { return "Password is very short"; } else { return null; } }, controller: passwodconttroler, keyboardType: TextInputType.visiblePassword, textAlignVertical: TextAlignVertical.bottom, obscureText: true, decoration: InputDecoration( hintText: "Password", filled: true, fillColor: Colors.white12, border: OutlineInputBorder( borderRadius: BorderRadius.circular(45), borderSide: BorderSide.none), ), ), ), Padding( padding: const EdgeInsets.only( left: 30, right: 30, bottom: 40), child: TextFormField( validator: (value) { if (value!.length > 20) { return "Password is very long"; } if (value.length < 7) { return "Password is very short"; } else { return null; } }, controller: conformpasswodconttroler, textAlignVertical: TextAlignVertical.bottom, obscureText: true, keyboardType: TextInputType.visiblePassword, decoration: InputDecoration( hintText: "Conform Password", filled: true, fillColor: Colors.white12, border: OutlineInputBorder( borderRadius: BorderRadius.circular(45), borderSide: BorderSide.none), ), ), ), ElevatedButton( onPressed: () { if (signUp() == null) { Navigator.of(context).pushReplacement( MaterialPageRoute( builder: (context) => const Screens())); } }, style: ElevatedButton.styleFrom( alignment: Alignment.center, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(30), ), backgroundColor: Colors.white, maximumSize: const Size(300, 65), minimumSize: const Size(300, 65), ), child: const DummyText( text: "Sign Up", size: 9, ), ), const SizedBox( height: 60, ) ], ), ), ], ), ]), )); } }
用户问题
我已将Firebase Realtime Database规则设置为true,并且重新下载了google-services.json文件,但数据库仍然没有任何数据写入,也无响应。
请协助我解决这个问题
问题分析与修复方案
你的代码存在几个核心逻辑错误,直接导致数据库写入失败:
1. 数据库写入逻辑位置错误+递归调用
在signUp()方法中,账号创建成功后会直接return credential,根本不会执行到函数末尾的数据库写入代码;同时你错误地递归调用signUp()来判断结果,会引发无限循环,完全偏离预期逻辑。
2. 异步方法处理错误
signUp()是异步方法,你在按钮点击事件中直接用if (signUp() == null)判断,这完全错误——异步方法返回的是Future对象,永远不会等于null,所以页面跳转逻辑永远不会触发。
修复后的完整代码
import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_database/firebase_database.dart'; import 'package:flutter/material.dart'; import '../app settings/text sittings.dart'; import '../screens.dart'; // ignore: must_be_immutable class SignUpPage extends StatefulWidget { const SignUpPage({Key? key}) : super(key: key); @override State<SignUpPage> createState() => _SignUpPageState(); } class _SignUpPageState extends State<SignUpPage> { final namecontroller = TextEditingController(); final emailcontroller = TextEditingController(); final passwodconttroler = TextEditingController(); final conformpasswodconttroler = TextEditingController(); GlobalKey<FormState> formstate = GlobalKey<FormState>(); final database = FirebaseDatabase.instance; Future<User?> signUp() async { var formdata = formstate.currentState; if (formdata!.validate()) { formdata.save(); if (passwordconfirmed()) { try { final UserCredential credential = await FirebaseAuth.instance.createUserWithEmailAndPassword( email: emailcontroller.text, password: passwodconttroler.text, ); // 账号创建成功后立即写入数据库 if (credential.user != null) { DatabaseReference ref = FirebaseDatabase.instance.ref("users"); await ref.child(credential.user!.uid).set({ "id": credential.user!.uid, "name": namecontroller.text, "email": emailcontroller.text, }); } return credential.user; } on FirebaseAuthException catch (e) { if (e.code == 'weak-password') { AwesomeDialog( context: context, dialogType: DialogType.warning, animType: AnimType.bottomSlide, title: '密码强度不足', body: const Text("密码过于简单")).show(); } else if (e.code == 'email-already-in-use') { AwesomeDialog( context: context, dialogType: DialogType.warning, animType: AnimType.bottomSlide, title: '账号已存在', body: const Text("该邮箱已注册过账号")).show(); } return null; } catch (e) { print(e); return null; } } } return null; } bool passwordconfirmed() { return passwodconttroler.text.trim() == conformpasswodconttroler.text.trim(); } void openSignScreen() { Navigator.of(context).pushReplacement( MaterialPageRoute(builder: (context) => const SignUpPage())); } @override void dispose() { super.dispose(); emailcontroller.dispose(); passwodconttroler.dispose(); conformpasswodconttroler.dispose(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white70, body: SafeArea( child: ListView(children: [ Stack( children: [ Form( key: formstate, child: Column( mainAxisAlignment: MainAxisAlignment.start, children: [ const SizedBox(height: 150, width: 60), const Text("Create Account", style: TextStyle( fontSize: 40, fontWeight: FontWeight.w800, fontFamily: 'Montserrat')), const SizedBox(height: 60, width: 20), Padding( padding: const EdgeInsets.only( left: 30, right: 30, bottom: 20), child: TextFormField( validator: (value) { if (value!.length > 20) return "名字过长"; if (value.length < 2) return "名字过短"; return null; }, controller: namecontroller, keyboardType: TextInputType.text, textAlignVertical: TextAlignVertical.bottom, decoration: InputDecoration( hintText: "Full Name", filled: true, fillColor: Colors.white12, border: OutlineInputBorder( borderRadius: BorderRadius.circular(45), borderSide: BorderSide.none), ), ), ), Padding( padding: const EdgeInsets.only( left: 30, right: 30, bottom: 20), child: TextFormField( validator: (value) { if (value!.isEmpty || !value.contains("@")) { return "请输入有效的邮箱"; } return null; }, controller: emailcontroller, keyboardType: TextInputType.emailAddress, textAlignVertical: TextAlignVertical.bottom, decoration: InputDecoration( hintText: "Email", filled: true, fillColor: Colors.white12, border: OutlineInputBorder( borderRadius: BorderRadius.circular(45), borderSide: BorderSide.none), ), ), ), Padding( padding: const EdgeInsets.only( left: 30, right: 30, bottom: 20), child: TextFormField( validator: (value) { if (value!.length > 20) return "密码过长"; if (value.length < 7) return "密码过短"; return null; }, controller: passwodconttroler, keyboardType: TextInputType.visiblePassword, textAlignVertical: TextAlignVertical.bottom, obscureText: true, decoration: InputDecoration( hintText: "Password", filled: true, fillColor: Colors.white12, border: OutlineInputBorder( borderRadius: BorderRadius.circular(45), borderSide: BorderSide.none), ), ), ), Padding( padding: const EdgeInsets.only( left: 30, right: 30, bottom: 40), child: TextFormField( validator: (value) { if (value != passwodconttroler.text) { return "两次输入的密码不一致"; } return null; }, controller: conformpasswodconttroler, textAlignVertical: TextAlignVertical.bottom, obscureText: true, keyboardType: TextInputType.visiblePassword, decoration: InputDecoration( hintText: "Conform Password", filled: true, fillColor: Colors.white12, border: OutlineInputBorder( borderRadius: BorderRadius.circular(45), borderSide: BorderSide.none), ), ), ), ElevatedButton( onPressed: () async { User? user = await signUp(); if (user != null) { Navigator.of(context).pushReplacement( MaterialPageRoute( builder: (context) => const Screens())); } }, style: ElevatedButton.styleFrom( alignment: Alignment.center, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(30), ), backgroundColor: Colors.white, maximumSize: const Size(300, 65), minimumSize: const Size(300, 65), ), child: const DummyText( text: "Sign Up", size: 9, ), ), const SizedBox(height: 60) ], ), ), ], ), ]), )); } }
额外优化说明
- 修正了表单验证的错误提示(比如名字输入框不再显示密码相关提示)
- 邮箱验证改为检查格式合法性
- 确认密码的验证逻辑更精准,直接对比密码输入框内容
- 数据库节点改为
users,用用户UID作为节点Key,符合Firebase最佳实践
内容的提问来源于stack exchange,提问作者ISLAM IS LIFE
相关产品推荐
相关产品推荐

