# #firebase #flutter #firebase-realtime-database #firebase-authentication
Вопрос:
Я прохожу курс Udemy по созданию приложения Uber. Я создал файл dart под названием VehicleInfo.dart, который можно увидеть ниже. По какой-то причине ни одна информация о моем автомобиле не сохраняется на базе огня. Если бы кто-нибудь мог помочь/указать, где я могу совершить ошибку, я был бы очень признателен. Заранее благодарю вас 🙂 ниже этого кода также находится мой файл signuppage.dart. После регистрации пользователь переходит на страницу с информацией о транспортном средстве. Ниже приведена необработанная ошибка исключения, которую я также получаю.
информация о транспортном средстве.дротик
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:cab_driver/BrandColors.dart';
import 'package:cab_driver/globalvariables.dart';
import 'package:cab_driver/screens/mainpage.dart';
import 'package:cab_driver/widgets/BrandButton.dart';
class VehicleInfo extends StatelessWidget {
final GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();
final FirebaseAuth _auth = FirebaseAuth.instance;
void showSnackBar(title, context) {
final SnackBar snackBar = SnackBar(
content: Text(
title,
textAlign: TextAlign.center,
style: TextStyle(fontSize: 15),
),
);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
static const String id = 'vehicleinfo';
var vehicleMakeController = TextEditingController();
var vehicleModelController = TextEditingController();
var vehicleColorController = TextEditingController();
var vehicleLicensePlateController = TextEditingController();
var driverLicenseIDNumberController = TextEditingController();
void updateProfile(context){
String id = currentFirebaseUser.uid;
DatabaseReference driverRef = FirebaseDatabase.instance.reference().child('drivers/$id/Vehicle_Details');
Map map = {
'Vehicle Make': vehicleMakeController.text,
'Vehicle Model': vehicleModelController,
'Vehicle Color': vehicleColorController,
'Vehicle License Plate': vehicleLicensePlateController,
'Driver License ID Number': driverLicenseIDNumberController,
};
driverRef.set(map);
Navigator.pushNamedAndRemoveUntil(context, MainPage.id, (route) => false);
}
@override
Widget build(BuildContext context) {
return Scaffold(
key: scaffoldKey,
body: SafeArea(
child: SingleChildScrollView(
child: Column(
children: <Widget>[
SizedBox(height: 20,),
Image.asset('./images/Sign_In_Logo.png', height: 110, width: 110,),
Padding(
padding: EdgeInsets.fromLTRB(20,20,20,30),
child: Column(
children: <Widget>[
SizedBox(height: 10,),
Text('Enter Vehicle Details',style: TextStyle(fontFamily: 'Montserrat', fontSize: 22),),
SizedBox(height: 25,),
// Vehicle Make
TextFormField(
controller: vehicleMakeController,
keyboardType: TextInputType.text,
decoration: InputDecoration(
labelText: 'Vehicle Make',
hintStyle: TextStyle(
color: Colors.grey,
fontSize: 14.0,
fontFamily: 'Montserrat',
)
),
style: TextStyle(fontSize: 14.0),
),
SizedBox(height: 10,),
// Vehicle Model
TextFormField(
controller: vehicleModelController,
keyboardType: TextInputType.text,
decoration: InputDecoration(
labelText: 'Vehicle Model',
hintStyle: TextStyle(
color: Colors.grey,
fontSize: 14.0,
fontFamily: 'Montserrat',
)
),
style: TextStyle(fontSize: 14.0),
),
SizedBox(height: 10,),
// Vehicle Color
TextFormField(
controller: vehicleColorController,
decoration: InputDecoration(
labelText: 'Vehicle Color',
hintStyle: TextStyle(
color: Colors.grey,
fontSize: 14.0,
fontFamily: 'Montserrat',
)
),
style: TextStyle(fontSize: 14.0),
),
SizedBox(height: 10,),
// Vehicle License Plate Number
TextFormField(
controller: vehicleLicensePlateController,
maxLength: 11,
decoration: InputDecoration(
counterText: '',
labelText: 'Vehicle License Plate',
hintStyle: TextStyle(
color: Colors.grey,
fontSize: 14.0,
fontFamily: 'Montserrat',
)
),
style: TextStyle(fontSize: 14.0),
),
SizedBox(height: 10,),
// Driver License ID Number
TextFormField(
controller: driverLicenseIDNumberController,
//keyboardType: TextInputType.text,
decoration: InputDecoration(
labelText: 'Driver License ID Number',
hintStyle: TextStyle(
color: Colors.grey,
fontSize: 14.0,
fontFamily: 'Montserrat',
)
),
style: TextStyle(fontSize: 14.0),
),
SizedBox(height: 40,),
BrandButton(
color: BrandColors.colorPrimary,
title: 'Register Vehicle',
onPressed: (){
if(vehicleMakeController.text.length < 3){
showSnackBar('Please provide a valid vehicle make', context);
return;
}
if(vehicleModelController.text.length < 2){
showSnackBar('Please provide a valid vehicle model', context);
return;
}
if(vehicleColorController.text.length < 3){
showSnackBar('Please provide a valid vehicle model', context);
return;
}
if(vehicleLicensePlateController.text.length < 5){
showSnackBar('Please provide a valid license plate', context);
return;
}
if(driverLicenseIDNumberController.text.length <9){
showSnackBar('Please provide a valid driver id number', context);
return;
}
updateProfile(context);
},
)
],
),
),
],
),
),
),
);
}
}
подписка.дротик
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:connectivity/connectivity.dart';
import 'package:cab_driver/BrandColors.dart';
import 'package:cab_driver/globalvariables.dart';
import 'package:cab_driver/screens/loginpage.dart';
import 'package:cab_driver/screens/mainpage.dart';
import 'package:cab_driver/screens/vehicleinfo.dart';
import 'package:cab_driver/widgets/ProgressDialog.dart';
import 'package:cab_driver/widgets/SkapeButton.dart';
import 'package:cab_driver/widgets/showsnackbar.dart';
class SignUpPage extends StatefulWidget {
static const String id = 'signup';
@override
_SignUpPageState createState() => _SignUpPageState();
}
class _SignUpPageState extends State<SignUpPage> {
final GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();
final FirebaseAuth _auth = FirebaseAuth.instance;
var _fullNameController = TextEditingController();
var _emailController = TextEditingController();
var _phoneNumberController = TextEditingController();
var _passwordController = TextEditingController();
var _confirmPasswordController = TextEditingController();
void signUpUser() async {
String authErrMsg;
// Show Please Wait Dialog
showDialog(
barrierDismissible: false,
context: context,
builder: (BuildContext context) => ProgressDialog(status: 'Signing you in...',),
);
try {
//final
User newUser = (await _auth.createUserWithEmailAndPassword(
email: _emailController.text,
password: _passwordController.text,
)).user;
// Check if user registration success
print('The new user:n$newUser');
Navigator.pop(context);
if(newUser != null){
showSnackBar('Registration Successful!', context);
print('Registration Successful!');
DatabaseReference newUserRef =
FirebaseDatabase.instance.reference().child('drivers/${newUser.uid}');
// Prepare data to be saved on users table
Map userMap = {
'fullname': _fullNameController.text,
'email': _emailController.text,
'password': _passwordController.text,
'cellphone': _phoneNumberController.text,
};
newUserRef.set(userMap);
currentFirebaseUser = newUser;
// Take user to main page
Navigator.pushNamed(context, VehicleInfo.id);
}
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
authErrMsg = 'The password provided is too weak';
print(authErrMsg);
showSnackBar(authErrMsg, context);
} else if (e.code == 'email-already-in-use') {
authErrMsg = 'An account already exists for that email';
print(authErrMsg);
showSnackBar(authErrMsg, context);
} else if (e.code == 'invalid-email') {
authErrMsg = 'Email address is invalid';
print(authErrMsg);
showSnackBar(authErrMsg, context);
}
} catch (e) {
print(e);
showSnackBar(e, context);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: SafeArea(
child: SingleChildScrollView(
child: Padding(
padding: EdgeInsets.all(3.0),
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
BackButton(
onPressed: (){
Navigator.pushNamedAndRemoveUntil(context, MainPage.id, (route) => false);
},
),
],
),
SizedBox(height: 10,),
Image(
alignment: Alignment.center,
height: 150.0,
width: 150.0,
image: AssetImage('./images/Sign_In_Logo.png'),
),
SizedBox(height: 5,),
Text('Landscaper Sign Up',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 25, fontFamily: 'Montserrat'),
),
Padding(
padding: EdgeInsets.all(12.0),
child: Column(
children: <Widget>[
// Full Name
TextFormField(
controller: _fullNameController,
keyboardType: TextInputType.text,
decoration: InputDecoration(
prefixIcon: Icon(Icons.person_outline),
labelText: 'Full Name',
labelStyle: TextStyle(
fontSize: 14.0,
fontFamily: 'Montserrat',
),
hintStyle: TextStyle(
color: Colors.grey,
fontSize: 12.0,
fontFamily: 'Montserrat',
)
),
style: TextStyle(fontSize: 14),
),
SizedBox(height: 10,),
// Email Address
TextFormField(
controller: _emailController,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
labelText: 'Email Address',
prefixIcon: Icon(Icons.email_outlined),
labelStyle: TextStyle(
fontSize: 14.0,
fontFamily: 'Montserrat',
),
hintStyle: TextStyle(
color: Colors.grey,
fontSize: 12.0,
fontFamily: 'Montserrat',
)
),
style: TextStyle(fontSize: 14),
),
SizedBox(height: 10,),
// Phone Number
TextFormField(
controller: _phoneNumberController,
keyboardType: TextInputType.phone,
decoration: InputDecoration(
labelText: 'Phone Number',
prefixIcon: Icon(Icons.local_phone_outlined),
labelStyle: TextStyle(
fontSize: 14.0,
fontFamily: 'Montserrat',
),
hintStyle: TextStyle(
color: Colors.grey,
fontSize: 12.0,
fontFamily: 'Montserrat',
)
),
style: TextStyle(fontSize: 14),
),
SizedBox(height: 10,),
// Password
TextFormField(
controller: _passwordController,
obscureText: true,
decoration: InputDecoration(
labelText: 'Password',
prefixIcon: Icon(Icons.lock_outline),
labelStyle: TextStyle(
fontSize: 14.0,
fontFamily: 'Montserrat',
),
hintStyle: TextStyle(
color: Colors.grey,
fontSize: 12.0,
fontFamily: 'Montserrat',
)
),
style: TextStyle(fontSize: 14),
),
SizedBox(height: 10,),
// Confirm Password
TextFormField(
controller: _confirmPasswordController,
obscureText: true,
decoration: InputDecoration(
labelText: 'Confirm Password',
prefixIcon: Icon(Icons.lock_open),
labelStyle: TextStyle(
fontSize: 14.0,
fontFamily: 'Montserrat',
),
hintStyle: TextStyle(
color: Colors.grey,
fontSize: 12.0,
fontFamily: 'Montserrat',
)
),
style: TextStyle(fontSize: 14),
),
SizedBox(height: 20,),
BrandButton(
title: 'SIGN UP',
color: BrandColors.colorPrimary,
onPressed: () async {
String authErrMsg;
var connectivityResult = await Connectivity().checkConnectivity();
if(connectivityResult != ConnectivityResult.mobile amp;amp; connectivityResult != ConnectivityResult.wifi){
authErrMsg = 'No Internet Connection';
print(authErrMsg);
showSnackBar(authErrMsg, context);
}
if (_passwordController.text != _confirmPasswordController.text) {
authErrMsg = 'Passwords Do Not Match';
print(authErrMsg);
showSnackBar(authErrMsg, context);
} else if (_fullNameController.text.length < 3){
authErrMsg = 'Please Provide A Valid Full Name';
print(authErrMsg);
showSnackBar(authErrMsg, context);
} else if (_phoneNumberController.text.length < 10){
authErrMsg = 'Please Provide A Valid Phone Number';
print(authErrMsg);
showSnackBar(authErrMsg, context);
} else {
signUpUser();
}
// signUpUser();
},
)
],
),
),
TextButton(
onPressed: () {
Navigator.pushNamedAndRemoveUntil(context, LoginPage.id, (route) => false);
},
child: Text.rich(
TextSpan(
text: 'Already a Driver? ',
style: TextStyle(
fontSize: 18,
color: Color(0xFF96A13A),
fontFamily: 'Montserrat',),
children: <TextSpan>[
TextSpan(
text: 'Log in',
style: TextStyle(
fontSize: 18,
color: Color(0xFF96A13A),
fontFamily: 'Montserrat',
decoration: TextDecoration.underline
)),
],
),
),
),
]
),
),
),
)
);
}
}
Необработанное Исключение:
flutter: Registration Successful!
[VERBOSE-2:ui_dart_state.cc(186)] Unhandled Exception: Invalid argument: Instance of 'TextEditingController'
#0 StandardMessageCodec.writeValue (package:flutter/src/services/message_codecs.dart:403:7)
#1 StandardMessageCodec.writeValue.<anonymous closure> (package:flutter/src/services/message_codecs.dart:400:9)
#2 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:397:8)
#3 StandardMessageCodec.writeValue (package:flutter/src/services/message_codecs.dart:398:13)
#4 StandardMessageCodec.writeValue.<anonymous closure> (package:flutter/src/services/message_codecs.dart:400:9)
#5 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:397:8)
#6 StandardMessageCodec.writeValue (package:flutter/src/services/message_codecs.dart:398:13)
#7 StandardMethodCodec.encodeMethodCall (package:flutter/src/services/message_codecs.dart:535:18)
#8 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:150:13)
#9 Meth<…>
Ответ №1:
Ошибка находится в блоке кода ниже:
Map map = {
'Vehicle Make': vehicleMakeController.text,
'Vehicle Model': vehicleModelController,
'Vehicle Color': vehicleColorController,
'Vehicle License Plate': vehicleLicensePlateController,
'Driver License ID Number': driverLicenseIDNumberController,
};
Вы передаете TextEditingController
экземпляр для модели транспортного средства, цвета транспортного средства, номерного знака транспортного средства и идентификационного номера водительского удостоверения.
Вам нужно использовать .text
геттер, чтобы получить фактическую строку от контроллеров. Кроме того, указание типов карт поможет вам определить ошибки в следующий раз.
Обновите определение map
выше до приведенного ниже, и оно должно исправить ошибку:
Map<String, String> map = {
'Vehicle Make': vehicleMakeController.text,
'Vehicle Model': vehicleModelController.text,
'Vehicle Color': vehicleColorController.text,
'Vehicle License Plate': vehicleLicensePlateController.text,
'Driver License ID Number': driverLicenseIDNumberController.text,
};
Комментарии:
1. Большое вам спасибо, я действительно ценю это. Это хорошо сработало!