ScaffoldMessenger的问题:在null上调用了“showSnackBar”方法
我希望你能帮助我。我正在尝试使用新方法来显示带有 ScaffoldMessenger 而不是 Scaffold 的 SnackBar。当我尝试运行它时,我遇到了这个问题:
======== Exception caught by gesture ===============================================================
The following NoSuchMethodError was thrown while handling a gesture:
The method 'showSnackBar' was called on null.
Receiver: null
Tried calling: showSnackBar(Instance of 'SnackBar')
这是我的代码:
import 'package:cab_rider/screens/loginpage.dart';
import 'package:cab_rider/widgets/TaxiButton.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
class RegistrationPage extends StatelessWidget {
static const String id = 'register';
var NombresController = TextEditingController();
var ApePaternoController = TextEditingController();
var ApeMaternoController= TextEditingController();
var EmailController = TextEditingController();
var TelefonoController = TextEditingController();
var PasswordController = TextEditingController();
var Password2Controller = TextEditingController();
final GlobalKey<ScaffoldMessengerState> scaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>();
void showSnack(String title){
final snackbar = SnackBar(
content: Text(title, textAlign: TextAlign.center, style: TextStyle(fontSize: 15,),)
);
scaffoldMessengerKey.currentState.showSnackBar(snackbar);
}
void registerUser() async {
try {
UserCredential userCredential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: EmailController.text,
password: PasswordController.text
);
if(userCredential != null){
print ('reg lista');
}
} 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);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
key: scaffoldMessengerKey,
backgroundColor: Colors.white,
body: SafeArea(
child: SingleChildScrollView(
child: Padding(
padding: EdgeInsets.all(8.0),
child: Column(
children: <Widget>[
SizedBox(height: 70,),
Image(
alignment: Alignment.center,
height: 100.0,
width: 100.0,
image: AssetImage('images/logo_pana.png'),
),
SizedBox(height: 40,),
Text('Crear una cuenta de gruero(a)',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 25, fontFamily: 'Brand-Bold'),
),
Padding(
padding: EdgeInsets.all(20.0),
child: Column(
children: <Widget>[
//Nombres
TextField(
controller: NombresController,
keyboardType: TextInputType.text,
decoration: InputDecoration(
labelText: 'Nombres',
labelStyle: TextStyle(
fontSize: 14.0,
),
hintStyle: TextStyle(
color: Colors.grey,
fontSize: 10.0
)
),
style: TextStyle(fontSize: 14),
),
SizedBox(height: 10,),
//ApePaterno
TextField(
controller: ApePaternoController,
keyboardType: TextInputType.text,
decoration: InputDecoration(
labelText: 'Apellido Paterno',
labelStyle: TextStyle(
fontSize: 14.0,
),
hintStyle: TextStyle(
color: Colors.grey,
fontSize: 10.0
)
),
style: TextStyle(fontSize: 14),
),
SizedBox(height: 10,),
//ApeMaterno
TextField(
controller: ApeMaternoController,
keyboardType: TextInputType.text,
decoration: InputDecoration(
labelText: 'Apellido Materno',
labelStyle: TextStyle(
fontSize: 14.0,
),
hintStyle: TextStyle(
color: Colors.grey,
fontSize: 10.0
)
),
style: TextStyle(fontSize: 14),
),
SizedBox(height: 10,),
//Email
TextField(
controller: EmailController,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
labelText: 'Correo',
labelStyle: TextStyle(
fontSize: 14.0,
),
hintStyle: TextStyle(
color: Colors.grey,
fontSize: 10.0
)
),
style: TextStyle(fontSize: 14),
),
SizedBox(height: 10,),
//Telefono
TextField(
controller: TelefonoController,
keyboardType: TextInputType.phone,
decoration: InputDecoration(
labelText: 'Número de teléfono',
labelStyle: TextStyle(
fontSize: 14.0,
),
hintStyle: TextStyle(
color: Colors.grey,
fontSize: 10.0
)
),
style: TextStyle(fontSize: 14),
),
SizedBox(height: 10,),
//Contraseña
TextField(
controller: PasswordController,
obscureText: true,
decoration: InputDecoration(
labelText: 'Contraseña',
labelStyle: TextStyle(
fontSize: 14.0,
),
hintStyle: TextStyle(
color: Colors.grey,
fontSize: 10.0
)
),
style: TextStyle(fontSize: 14),
),
SizedBox(height: 10,),
//Confirmar Contraseña
TextField(
controller: Password2Controller,
obscureText: true,
decoration: InputDecoration(
labelText: 'Reingresar Contraseña',
labelStyle: TextStyle(
fontSize: 14.0,
),
hintStyle: TextStyle(
color: Colors.grey,
fontSize: 10.0
)
),
style: TextStyle(fontSize: 14),
),
SizedBox(height: 40,),
TaxiButton(
title: 'REGISTRAR',
color: Colors.deepPurple,
onPressed: (){
//verificar datos
if(NombresController.text.length < 3){
showSnack('Nombre demasiado corto.');
return;
}
if(TelefonoController.text.length < 9){
showSnack('Número inválido.');
return;
}
if(EmailController.text.contains('@')){
showSnack('Ingrese un correo válido.');
return;
}
if(PasswordController.text.length < 8){
showSnack('La contraseña debe tener mínimo 8 carácteres.');
return;
}
registerUser();
}
)
],
),
),
FlatButton(
onPressed: (){
Navigator.pushNamedAndRemoveUntil(context, LoginPage.id, (route) => false);
},
child: Text('¿Ya tienes una cuenta?. Ingresa aquí!'))
],
),
),
),
),
);
}
}
我已经阅读了同一问题的一些答案,但他们使用的版本并不是最新的。Flutter 改变了显示小吃店的旧方式,改为 ScaffoldMessenger,我非常菜鸟。
回答
您可以复制粘贴运行下面的完整代码
您可以使用ScaffoldMessenger,您可以从
return Scaffold(
key: scaffoldMessengerKey,
到
return ScaffoldMessenger(
key: scaffoldMessengerKey,
child: Scaffold(
工作演示
完整代码
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
class RegistrationPage extends StatelessWidget {
static const String id = 'register';
var NombresController = TextEditingController();
var ApePaternoController = TextEditingController();
var ApeMaternoController = TextEditingController();
var EmailController = TextEditingController();
var TelefonoController = TextEditingController();
var PasswordController = TextEditingController();
var Password2Controller = TextEditingController();
final GlobalKey<ScaffoldMessengerState> scaffoldMessengerKey =
GlobalKey<ScaffoldMessengerState>();
void showSnack(String title) {
final snackbar = SnackBar(
content: Text(
title,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 15,
),
));
scaffoldMessengerKey.currentState.showSnackBar(snackbar);
}
void registerUser() async {
try {
UserCredential userCredential = await FirebaseAuth.instance
.createUserWithEmailAndPassword(
email: EmailController.text, password: PasswordController.text);
if (userCredential != null) {
print('reg lista');
}
} 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);
}
}
@override
Widget build(BuildContext context) {
return ScaffoldMessenger(
key: scaffoldMessengerKey,
child: Scaffold(
backgroundColor: Colors.white,
body: SafeArea(
child: SingleChildScrollView(
child: Padding(
padding: EdgeInsets.all(8.0),
child: Column(
children: <Widget>[
SizedBox(
height: 70,
),
Image(
alignment: Alignment.center,
height: 100.0,
width: 100.0,
image: NetworkImage('https://picsum.photos/250?image=9'),
),
SizedBox(
height: 40,
),
Text(
'Crear una cuenta de gruero(a)',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 25, fontFamily: 'Brand-Bold'),
),
Padding(
padding: EdgeInsets.all(20.0),
child: Column(
children: <Widget>[
//Nombres
TextField(
controller: NombresController,
keyboardType: TextInputType.text,
decoration: InputDecoration(
labelText: 'Nombres',
labelStyle: TextStyle(
fontSize: 14.0,
),
hintStyle: TextStyle(
color: Colors.grey, fontSize: 10.0)),
style: TextStyle(fontSize: 14),
),
SizedBox(
height: 10,
),
//ApePaterno
TextField(
controller: ApePaternoController,
keyboardType: TextInputType.text,
decoration: InputDecoration(
labelText: 'Apellido Paterno',
labelStyle: TextStyle(
fontSize: 14.0,
),
hintStyle: TextStyle(
color: Colors.grey, fontSize: 10.0)),
style: TextStyle(fontSize: 14),
),
SizedBox(
height: 10,
),
//ApeMaterno
TextField(
controller: ApeMaternoController,
keyboardType: TextInputType.text,
decoration: InputDecoration(
labelText: 'Apellido Materno',
labelStyle: TextStyle(
fontSize: 14.0,
),
hintStyle: TextStyle(
color: Colors.grey, fontSize: 10.0)),
style: TextStyle(fontSize: 14),
),
SizedBox(
height: 10,
),
//Email
TextField(
controller: EmailController,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
labelText: 'Correo',
labelStyle: TextStyle(
fontSize: 14.0,
),
hintStyle: TextStyle(
color: Colors.grey, fontSize: 10.0)),
style: TextStyle(fontSize: 14),
),
SizedBox(
height: 10,
),
//Telefono
TextField(
controller: TelefonoController,
keyboardType: TextInputType.phone,
decoration: InputDecoration(
labelText: 'Número de teléfono',
labelStyle: TextStyle(
fontSize: 14.0,
),
hintStyle: TextStyle(
color: Colors.grey, fontSize: 10.0)),
style: TextStyle(fontSize: 14),
),
SizedBox(
height: 10,
),
//Contraseña
TextField(
controller: PasswordController,
obscureText: true,
decoration: InputDecoration(
labelText: 'Contraseña',
labelStyle: TextStyle(
fontSize: 14.0,
),
hintStyle: TextStyle(
color: Colors.grey, fontSize: 10.0)),
style: TextStyle(fontSize: 14),
),
SizedBox(
height: 10,
),
//Confirmar Contraseña
TextField(
controller: Password2Controller,
obscureText: true,
decoration: InputDecoration(
labelText: 'Reingresar Contraseña',
labelStyle: TextStyle(
fontSize: 14.0,
),
hintStyle: TextStyle(
color: Colors.grey, fontSize: 10.0)),
style: TextStyle(fontSize: 14),
),
SizedBox(
height: 40,
),
TextButton(
child: Text('REGISTRAR'),
//color: Colors.deepPurple,
onPressed: () {
//verificar datos
if (NombresController.text.length < 3) {
showSnack('Nombre demasiado corto.');
return;
}
if (TelefonoController.text.length < 9) {
showSnack('Número inválido.');
return;
}
if (EmailController.text.contains('@')) {
showSnack('Ingrese un correo válido.');
return;
}
if (PasswordController.text.length < 8) {
showSnack(
'La contraseña debe tener mínimo 8 carácteres.');
return;
}
registerUser();
})
],
),
),
FlatButton(
onPressed: () {
//Navigator.pushNamedAndRemoveUntil(context, LoginPage.id, (route) => false);
},
child: Text('¿Ya tienes una cuenta?. Ingresa aquí!'))
],
),
),
),
),
),
);
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: RegistrationPage(),
);
}
}
THE END
二维码