我正在使用Flutter使用Firebase身份验证来制作注册表单,但是当我尝试使用Scaffold.of(context).showSnackBar SnackBar(content: Text(e.message)
的“注册”小部件向用户显示注册错误消息时,当我尝试处理身份验证时,此消息一直显示< / p>
首先,我创建了一个auth.dart文件
import 'package:firebase_auth/firebase_auth.dart';
class Auth {
final FirebaseAuth _auth = FirebaseAuth.instance;
//Sign up method
Future SignupClass(String email, String password) async {
final UserCredential user = await _auth.createUserWithEmailAndPassword(
email: email, password: password);
}
然后我创建了这个TextField类以模块化我的代码
class Textfield extends StatelessWidget {
final String hint;
final IconData icon;
final Function savingData;
String _emptyMessage(String str) {
switch (hint) {
case 'Enter your name':
return 'Name is required';
case 'Enter your e-mail':
return 'Email is required';
case 'Enter your Password':
return 'Password is required';
}
}
Textfield(
{@required this.savingData, @required this.hint, @required this.icon});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: TextFormField(
validator: (value) {
if (value.isEmpty) {
return _emptyMessage(hint);
}
return null;
},
onSaved: savingData
}}
这是Sig-up小部件
class SignupScreen extends StatelessWidget {
static String id = '/SignupScreen';
GlobalKey<FormState> _globalKey = GlobalKey<FormState>();
String _email, _password, _name;
final _auth = Auth();
@override
Widget build(BuildContext context) {
return Scaffold(Textfield(
hint: 'Enter your name',
icon: Icons.person,
savingData: (value) {
_name = value;
},
),
SizedBox(
height: height * .02,
),
Textfield(
hint: 'Enter your e-mail',
icon: Icons.email,
savingData: (value) {
_email =value;
},
),
SizedBox(
height: height * .02,
),
Textfield(
hint: 'Enter your Password',
icon: Icons.lock,
savingData: (value) {
_password = value;
},
),
SizedBox(
height: height * .05,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 120.0),
child: Builder(
builder: (context) => RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0)),
child: Text(
'Register',
style: TextStyle(color: Colors.white),
),
color: Colors.black,
onPressed: () async {
if (_globalKey.currentState.validate()) {
try {
await _auth.SignupClass(_email, _password);
_globalKey.currentState.save();
}on FirebaseException catch (e) {
print(e.toString());
Scaffold.of(context).showSnackBar(
SnackBar(
content: Text(e.message),
),
);
}
}
}),
),
),
)
}
and I wrapped my main function with Firebase Initialize
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
答案 0 :(得分:0)
您需要将您的窗口小部件转换为StatefulWidget,并在文本字段的onChanged方法上调用setState()。因为,在调用构建之前,窗口小部件的状态不会更新,因此您的_email,_password和_name字段将永远不会更新。这样可以解决您的问题,但是有更好的方法可以解决此问题。
有许多状态管理库可以极大地帮助将这种状态保持在UI之外(通常,最好将任何非UI状态与UI分开)。以下是一些建议:
您可以查看YouTube上的许多教程。我推荐的一些是AndyJulow,ResoCoder和MarcusNg。