Flutter: LateInitializationError: Field '_name' has not been initialized - flutter

I recently use to using firebase core made some changes to my code that I don't quite understand. I'm new to programming flutter. Any way, I've tried reading this similar thread here about it but I still don't quite understand it. Can someone please provide an example code of what's needed to solve for the error below?
Firebase.dart
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:mybankapp/routscreens/routwidget.dart';
class FirebaseAuthMethods {
final _firestore = FirebaseFirestore.instance;
final _firebaseAuth = FirebaseAuth.instance;
//Email Registration
Future<void> signUpWithEmail({
required String name,
required String email,
required String password,
}) async {
await _firebaseAuth.createUserWithEmailAndPassword(
email: email,
password: password,
);
await sendEmailVerification();
await _firestore
.collection('users')
.doc(FirebaseAuth.instance.currentUser!.uid)
.set({
'Name': name,
'email': email,
});
}
//Email Login
Future<void> loginWithEmail({
required String email,
required String password,
}) async {
try{
await _firebaseAuth.signInWithEmailAndPassword(
email: email,
password: password,
);
if (!_firebaseAuth.currentUser!.emailVerified){
await sendEmailVerification();
//show mail not verified and mail verification is sent again.
}else {
NavigationBarBottom();
//Show Home Page
}
} on FirebaseAuthException catch (e){
e.message!;
//show snackbar for error mwssage
}
}
//Email Verification
Future<void> sendEmailVerification() async{
try{
_firebaseAuth.currentUser!.sendEmailVerification();
//Snackbar for Verification Mail
} on FirebaseAuthException catch(e){
//Snackbar for error email msg
}
}
}
SignUpPage.dart
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mybankapp/authscreens/loginscreen.dart';
import 'package:mybankapp/colors/colors.dart';
import 'package:mybankapp/routscreens/routwidget.dart';
import 'package:mybankapp/textfontfamily/textfontfamily.dart';
import 'package:mybankapp/welcomescreen/welcomescreen.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:mybankapp/firebase_services/firebase_auth';
class SignUpScreen extends StatefulWidget {
#override
_SignUpScreenState createState() => _SignUpScreenState();
}
class _SignUpScreenState extends State<SignUpScreen> {
final _formKey = GlobalKey<FormState>();
final FirebaseAuthMethods firebaseAuthMethods = FirebaseAuthMethods();
late String _name;
late String _emailAddress = '';
late String _password;
late String _confirmPassword;
final bool _isLoading = false;
void signUpUser() async {
try {
firebaseAuthMethods.signUpWithEmail(
name: _name,
email: _emailAddress,
password: _password,
);
} on FirebaseAuthException catch (e) {
print(e.message!);
//Snackbar for error mail
}
//NavigationBarBottom();
}
Text text(String text) {
return Text(
text,
style: TextStyle(
fontSize: 10,
fontFamily: TextFontFamily.helveticaNeueCyrRoman,
color: ColorResources.white,
),
);
}
TextFormField textFormField(String hint, String? Function(String?) validator,
void Function(String?) onSaved,
{bool obscureText = false}) {
return TextFormField(
style: TextStyle(
fontFamily: TextFontFamily.helveticaNeueCyrRoman,
fontSize: 13,
color: ColorResources.grey2,
),
obscureText: obscureText,
cursorColor: ColorResources.blue1,
decoration: InputDecoration(
filled: true,
fillColor: ColorResources.grey1.withOpacity(0.05),
hintText: hint,
isDense: true,
hintStyle: TextStyle(
fontFamily: TextFontFamily.helveticaNeueCyrRoman,
fontSize: 13,
color: ColorResources.grey2,
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(5),
borderSide: BorderSide(
width: 1,
color: ColorResources.blue1.withOpacity(0.6),
),
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5),
borderSide: BorderSide(
width: 1,
color: ColorResources.blue1.withOpacity(0.6),
),
),
errorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(5),
borderSide: BorderSide(
width: 1,
color: ColorResources.blue1.withOpacity(0.6),
),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(5),
borderSide: BorderSide(
width: 1,
color: ColorResources.blue1.withOpacity(0.6),
),
),
),
validator: validator,
onSaved: onSaved,
);
}
// emailAddress validation
// ignore: valid_regexps
final _emailAddressRegExp =
RegExp(r'^.+#[a-zA-Z]+\.{1}[a-zA-Z]+(\.{0,1}[a-zA-Z]+)$');
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: ColorResources.backGroundColor,
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.only(top: 50, left: 15, right: 15),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
InkWell(
onTap: () {
Get.off(WelcomeScreen());
},
child: Icon(
Icons.close,
color: ColorResources.white,
),
),
SizedBox(height: 70),
Text(
"Create Account",
style: TextStyle(
fontFamily: TextFontFamily.helveticNeueCyrBold,
fontSize: 35,
color: ColorResources.red),
),
SizedBox(height: 7),
Text(
"Open a Noble Bank account with a few details.",
style: TextStyle(
fontFamily: TextFontFamily.helveticaNeueCyrRoman,
fontSize: 15,
color: ColorResources.white1),
),
SizedBox(height: 40),
Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
text("Full name"),
SizedBox(height: 10),
textFormField("", (value) {
if (value!.isEmpty) {
return "Please enter your name";
}
return null;
}, (value) {
_name = value!;
}),
SizedBox(height: 20),
text("Email Address"),
SizedBox(height: 10),
textFormField("", (value) {
if (!_emailAddressRegExp.hasMatch(value!)) {
return "Please enter your email address";
}
return null;
}, (value) {
_emailAddress = value!;
}),
SizedBox(height: 20),
text("Password"),
SizedBox(height: 10),
textFormField("", (value) {
if (value!.isEmpty) {
return "Please enter your password";
} else if (value.length < 8) {
return "Password must be at least 8 characters long";
}
return null;
}, (value) {
_password = value!;
}, obscureText: true),
SizedBox(height: 20),
text("Repeat password"),
SizedBox(height: 10),
textFormField("", (value) {
if (value!.isEmpty) {
return "Please enter your password";
} else if (value != _password) {
return "Password doesn't match";
}
return null;
}, (value) {
_confirmPassword = value!;
}, obscureText: true),
],
),
),
SizedBox(height: Get.height >= 876 ? 150 : 50),
_isLoading
? CircularProgressIndicator()
: SizedBox(
width: double.infinity,
child: InkWell(
onTap: signUpUser,
child: Container(
height: 50,
width: Get.width,
decoration: BoxDecoration(
color: ColorResources.red,
borderRadius: BorderRadius.circular(10),
),
child: Center(
child: Text(
"CREATE YOUR FREE ACCOUNT",
style: TextStyle(
fontFamily:
TextFontFamily.helveticaNeueCyrRoman,
fontWeight: FontWeight.w700,
fontSize: 13.5,
color: ColorResources.white),
),
),
),
),
),
SizedBox(height: 20),
Center(
child: RichText(
text: TextSpan(
text: "Do you already have a Noble Bank account?",
style: TextStyle(
fontSize: 13.5,
fontWeight: FontWeight.w300,
fontFamily: TextFontFamily.helveticaNeueCyrRoman,
color: ColorResources.white2,
),
children: <TextSpan>[
TextSpan(
recognizer: TapGestureRecognizer()
..onTap = () => Get.to(LogInScreen()),
text: " Sign in here",
style: TextStyle(
fontSize: 14,
fontFamily: TextFontFamily.helveticaNeueCyrRoman,
fontWeight: FontWeight.w300,
color: ColorResources.red,
),
),
],
),
),
),
],
),
),
),
);
}
}

If you cannot guarantee that _name (and the other fields) are set to a valid value before you call signUpUser(), you should not make the late.
Instead, make them nullable as in
String? _name;
And check for non-null values bevor using the data to create the user account.

Related

Duplicate global key detected in widget tree

I am facing a problem duplicate global key detected in widget tree when I use static keyword with global key.
If I don't use this static keyword then keyboard hides automatically after few seconds. What should I do?
This is the code that I have tried
`import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:email_validator/email_validator.dart';
import 'package:semesterproject/forgetpassword.dart';
import 'package:semesterproject/home.dart';
import 'package:semesterproject/signup.dart';
import 'package:semesterproject/textfielddec.dart';
class login extends StatelessWidget {
const login({super.key});
#override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.purpleAccent,
Colors.lightBlue,
Colors.indigoAccent
]),
),
child: Scaffold(
backgroundColor: Colors.transparent,
body: Center(
child: Container(
height: MediaQuery.of(context).size.height * 0.7,
width: MediaQuery.of(context).size.width * 0.8,
child: CustomForm(),
))),
);
}
}
class CustomForm extends StatefulWidget {
const CustomForm({super.key});
#override
State<CustomForm> createState() => _CustomFormState();
}
class _CustomFormState extends State<CustomForm> {
static final _formkey = GlobalKey<FormState>();
final TextEditingController passcontroller = TextEditingController();
final TextEditingController emailcontroller = TextEditingController();
bool passvisibility = true;
FirebaseAuth _auth = FirebaseAuth.instance;
var errormessage1 = null, errormessage2 = null;
void setpassvisibility() {
setState(() {
passvisibility = !passvisibility;
});
}
Future<void> login() async {
if (_formkey.currentState!.validate()) {
_formkey.currentState!.save();
try {
await _auth
.signInWithEmailAndPassword(
email: emailcontroller.text, password: passcontroller.text)
.then((value) => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Homepage(),
)));
} on FirebaseAuthException catch (error) {
if (error.code == 'wrong-password') {
setState(() {
errormessage1 = "Incorrect Password!";
});
} else {
setState(() {
errormessage1 = null;
});
}
if (error.code == 'user-not-found') {
setState(() {
errormessage2 = "User email not found";
});
} else {
setState(() {
errormessage2 = null;
});
}
}
}
}
#override
Widget build(BuildContext context) {
return Form(
key: _formkey,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
"Login to your Account",
style: TextStyle(
fontSize: 31,
fontWeight: FontWeight.bold,
color: Colors.cyanAccent),
),
SizedBox(
width: MediaQuery.of(context).size.width,
child: TextFormField(
controller: emailcontroller,
style: TextStyle(fontSize: 22),
decoration: InputDecoration(
errorText: errormessage2,
focusedBorder: getfocusedborder(),
enabledBorder: getenabledborder(),
errorBorder: geterrorborder(),
focusedErrorBorder: geterrorfocusedborder(),
hintText: "Email",
hintStyle: TextStyle(fontSize: 22),
errorStyle: TextStyle(fontSize: 18),
),
validator: (value) {
if (value!.isEmpty) return "this field is required";
if (EmailValidator.validate(value) == false)
return "Please enter a valid email";
return null;
},
),
),
SizedBox(
width: MediaQuery.of(context).size.width,
child: TextFormField(
style: TextStyle(fontSize: 22),
controller: passcontroller,
obscureText: passvisibility,
decoration: InputDecoration(
errorText: errormessage1,
focusedBorder: getfocusedborder(),
enabledBorder: getenabledborder(),
errorBorder: geterrorborder(),
focusedErrorBorder: geterrorfocusedborder(),
hintText: "Password",
hintStyle: TextStyle(fontSize: 22),
errorStyle: TextStyle(fontSize: 18),
suffixIcon: IconButton(
onPressed: setpassvisibility,
icon: passvisibility
? Icon(
Icons.visibility_off,
color: Colors.black,
)
: Icon(Icons.visibility),
color: Colors.black,
)),
validator: (value) {
if (value!.isEmpty) return "this field is required";
return null;
},
),
),
InkWell(
child: Text("Forgot password?",
style: TextStyle(color: Colors.amberAccent, fontSize: 22)),
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => forgetpass(),
)),
),
SizedBox(
width: 280,
height: 50,
child: ElevatedButton(
onPressed: () => login(),
child: Text(
"Login",
style: TextStyle(fontSize: 22),
),
style: ElevatedButton.styleFrom(backgroundColor: Colors.indigo),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"Don't have an account?",
style: TextStyle(fontSize: 22, color: Colors.amberAccent),
textAlign: TextAlign.center,
),
InkWell(
child: Text("Signup",
style: TextStyle(color: Colors.amber, fontSize: 20)),
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Signup(),
)),
)
],
),
],
),
);
}
}`
I have go through with different posts of this error but I can't get the solution

how to reset the password if user forgot the password in firebase and flutter

I want to reset the forgot password inside app using flutter. I have email verification screen then I use to get an otp that verifies the email after email verification I want to move to new password screen which takes new password as input and resets the password.
How to achive this using firebase flutter?
Check this. you will get password reset email to the email address that is sent to firebase
firebase_exceptions.dart
import 'package:firebase_auth/firebase_auth.dart';
enum AuthStatus {
successful,
wrongPassword,
emailAlreadyExists,
invalidEmail,
weakPassword,
unknown,
}
class AuthExceptionHandler {
static handleAuthException(FirebaseAuthException e) {
AuthStatus status;
switch (e.code) {
case "invalid-email":
status = AuthStatus.invalidEmail;
break;
case "wrong-password":
status = AuthStatus.wrongPassword;
break;
case "weak-password":
status = AuthStatus.weakPassword;
break;
case "email-already-in-use":
status = AuthStatus.emailAlreadyExists;
break;
default:
status = AuthStatus.unknown;
}
return status;
}
static String generateErrorMessage(error) {
String errorMessage;
switch (error) {
case AuthStatus.invalidEmail:
errorMessage = "Your email address appears to be malformed.";
break;
case AuthStatus.weakPassword:
errorMessage = "Your password should be at least 6 characters.";
break;
case AuthStatus.wrongPassword:
errorMessage = "Your email or password is wrong.";
break;
case AuthStatus.emailAlreadyExists:
errorMessage =
"The email address is already in use by another account.";
break;
default:
errorMessage = "An error occured. Please try again later.";
}
return errorMessage;
}
}
reset_password.dart
import 'package:firebase_auth/firebase_auth.dart';
import 'package:school/screens/firebase_exception.dart';
class ResetPasswordScreen extends StatefulWidget {
static const String id = 'reset_password';
const ResetPasswordScreen({Key? key}) : super(key: key);
#override
State<ResetPasswordScreen> createState() => _ResetPasswordScreenState();
}
class _ResetPasswordScreenState extends State<ResetPasswordScreen> {
final _key = GlobalKey<FormState>();
final _emailController = TextEditingController();
static final auth = FirebaseAuth.instance;
static late AuthStatus _status;
#override
void dispose() {
_emailController.dispose();
super.dispose();
}
Future<AuthStatus> resetPassword({required String email}) async {
await auth
.sendPasswordResetEmail(email: email)
.then((value) => _status = AuthStatus.successful)
.catchError(
(e) => _status = AuthExceptionHandler.handleAuthException(e));
return _status;
}
#override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
return Scaffold(
body: Container(
width: size.width,
height: size.height,
color: Colors.white,
child: Padding(
padding: const EdgeInsets.only(
left: 16.0, right: 16.0, top: 50.0, bottom: 25.0),
child: Form(
key: _key,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
GestureDetector(
onTap: () => Navigator.pop(context),
child: const Icon(Icons.close),
),
const SizedBox(height: 70),
const Text(
"Forgot Password",
style: TextStyle(
fontSize: 35,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
const SizedBox(height: 10),
const Text(
'Please enter your email address to recover your password.',
style: TextStyle(
fontSize: 15,
color: Colors.black,
),
),
const SizedBox(height: 40),
const Text(
'Email address',
style: TextStyle(
fontSize: 15,
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 10),
Container(
child: TextFormField(
obscureText: false,
controller: _emailController,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Empty email';
}
return null;
},
autofocus: false,
style: const TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
color: kDarkGrey),
decoration: const InputDecoration(
contentPadding:
EdgeInsets.symmetric(vertical: 20, horizontal: 20),
border: OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(30.0))),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: kBlackText,
width: 1,
),
borderRadius: BorderRadius.all(
Radius.circular(
30.0,
),
),
),
focusedBorder: OutlineInputBorder(
borderSide:
BorderSide(color: kSecondaryColor, width: 2.0),
borderRadius: BorderRadius.all(
Radius.circular(
30.0,
),
),
),
isDense: true,
// fillColor: kPrimaryColor,
filled: true,
errorStyle: TextStyle(fontSize: 15),
hintText: 'email address',
hintStyle: TextStyle(
fontSize: 17,
fontWeight: FontWeight.bold,
color: kLightWhiteGray),
),
),
),
const SizedBox(height: 16),
const Expanded(child: SizedBox()),
SizedBox(
height: MediaQuery.of(context).size.height / 20,
child: Material(
elevation: 2,
borderRadius: BorderRadius.circular(20),
color: kSecondaryColor,
child: MaterialButton(
onPressed: () async {
if (_key.currentState!.validate()) {
final _status = await resetPassword(
email: _emailController.text.trim());
if (_status == AuthStatus.successful) {
//your logic
} else {
//your logic or show snackBar with error message
}
}
},
minWidth: double.infinity,
child: const Text(
'RECOVER PASSWORD',
style: TextStyle(
color: kBlackText,
fontWeight: FontWeight.bold,
fontSize: 16,
fontFamily: 'Poppins'),
),
),
),
),
const SizedBox(height: 20),
],
),
),
),
),
);
}
}
What you're describing doesn't sound like resetting a password, but rather just setting their password. If that's indeed the case, have a look at the documentation on setting the password for the user.
If you really want to reset the user's password, have a look at the documentation on sending a password reset email. Note that there are very few options to customize this flow though

Null check operator used on a null value when login to the app

I am trying to login with cubit and api So i did every thing and the model of login so when I click on login there are 2 errors shows to me
1- Null check operator used on a null value
and this one shows when I make the login model variable ?
and the second one when I sit the login model late
2- LateInitializationError: Field 'loginModel' has not been initialized.
this is my cubit
// ignore_for_file: avoid_print
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:sa/cubit/login_cubit/login_states.dart';
import 'package:sa/modules/login_model/login_model.dart';
import 'package:sa/network/dio_helper/dio_helper.dart';
import 'package:sa/network/end_points.dart';
import 'package:sa/styles/color/color.dart';
class LoginCubit extends Cubit<LoginStates> {
LoginCubit() : super(LoginInitislState());
static LoginCubit get(context) => BlocProvider.of(context);
var suffix = Icon(Icons.visibility_outlined, color: defaultColor);
bool isPassword = false;
void changeVisibilty() {
isPassword = !isPassword;
if (isPassword == false) {
suffix = Icon(Icons.visibility_off_outlined, color: defaultColor);
} else {
suffix = Icon(Icons.visibility_outlined, color: defaultColor);
}
emit(LoginChangeIconState());
}
LoginModel? loginModel;
void userData({
required email,
required password,
}) {
emit(LoginLoadingInitialStat());
DioHelper.postData(
url: LOGIN,
data: {
'email': email,
'password': password,
},
).then((value) {
loginModel = LoginModel.fromJson(value.data);
print('message is ${loginModel!.message!}');
print('Your token is ${loginModel!.data!.token!}');
print('login done');
emit(LoginSuccessState(loginModel!));
}).catchError((error) {
emit(LoginFailedState(error.toString()));
print('error when login in cubit ${error.toString()}');
});
}
}
and this is my states
import 'package:sa/modules/login_model/login_model.dart';
abstract class LoginStates{}
class LoginInitislState extends LoginStates{}
class LoginChangeIconState extends LoginStates{}
class LoginLoadingInitialStat extends LoginStates{}
class LoginSuccessState extends LoginStates
{
final LoginModel loginModel;
LoginSuccessState(this.loginModel);
}
class LoginFailedState extends LoginStates{
final String error;
LoginFailedState(this.error);
}
and this is the design of the login page
// ignore_for_file: must_be_immutable, avoid_print
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:sa/cubit/login_cubit/login_cubit.dart';
import 'package:sa/cubit/login_cubit/login_states.dart';
import 'package:sa/network/cache_helper/cache_helper.dart';
import 'package:sa/network/components/component.dart';
import 'package:sa/styles/color/color.dart';
class LoginScreen extends StatelessWidget {
LoginScreen({super.key});
var emailController = TextEditingController();
var passwordController = TextEditingController();
var formKey = GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
return BlocConsumer<LoginCubit, LoginStates>(
listener: (context, state) {
if (state is LoginSuccessState) {
if (state.loginModel.status!) {
print(state.loginModel.message);
print(state.loginModel.status);
CachceHelper.saveData(
key: 'token',
value: state.loginModel.data!.token,
).then((value) {
showToast(
msg: state.loginModel.message!, state: ToastState.success);
});
} else {
print(state.loginModel.message);
showToast(msg: state.loginModel.message!, state: ToastState.error);
}
}
},
builder: (context, state) {
return Scaffold(
appBar: AppBar(
title: const Center(
child: Text(
'Social App',
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
),
),
body: Padding(
padding: const EdgeInsets.all(20.0),
child: SingleChildScrollView(
child: Form(
key: formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'LOGIN',
style: Theme.of(context).textTheme.headline4!.copyWith(
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
const SizedBox(
height: 20.0,
),
Text(
'Login Now To Be One Of Us',
style: TextStyle(
color: Colors.grey[600],
fontSize: 20.0,
fontWeight: FontWeight.bold,
),
),
const SizedBox(
height: 30.0,
),
TextFormField(
controller: emailController,
keyboardType: TextInputType.emailAddress,
validator: (value) {
if (value!.isEmpty) {
return 'Please Enter Your Email';
}
return null;
},
onFieldSubmitted: (value) {},
decoration: InputDecoration(
label: Text(
'Email Address',
style: TextStyle(
fontSize: 15.0,
color: defaultColor,
fontWeight: FontWeight.bold,
),
),
prefixIcon: Icon(
Icons.email,
color: defaultColor,
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
),
const SizedBox(
height: 30.0,
),
TextFormField(
controller: passwordController,
keyboardType: TextInputType.visiblePassword,
validator: (value) {
if (value!.isEmpty) {
return 'Please Enter Your Password';
}
return null;
},
obscureText: LoginCubit.get(context).isPassword,
onTap: () {
LoginCubit.get(context).changeVisibilty();
},
onFieldSubmitted: (value) {
if (formKey.currentState!.validate()) {
LoginCubit.get(context).userData(
email: emailController.text,
password: passwordController.text,
);
}
},
decoration: InputDecoration(
label: Text(
'Password',
style: TextStyle(
fontSize: 15.0,
color: defaultColor,
fontWeight: FontWeight.bold,
),
),
prefixIcon: Icon(
Icons.lock,
color: defaultColor,
),
suffixIcon: LoginCubit.get(context).suffix,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
),
const SizedBox(
height: 20.0,
),
Container(
width: double.infinity,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: defaultColor,
),
child: TextButton(
onPressed: () {
if (formKey.currentState!.validate()) {
CachceHelper.saveData(
key: 'token',
value: LoginCubit.get(context)
.loginModel!
.data!
.token!,
).then((value) {
showToast(
msg:
LoginCubit.get(context).loginModel!.message!,
state: ToastState.success,
);
});
LoginCubit.get(context).userData(
email: emailController.text,
password: passwordController.text,
);
}
},
child: const Text(
'Login',
style: TextStyle(
color: Colors.white,
fontSize: 17.0,
fontWeight: FontWeight.bold,
),
),
),
),
const SizedBox(
height: 15.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'Don\'t have an account?',
style: TextStyle(
fontSize: 17.0,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
TextButton(
onPressed: () {},
child: Text(
'REGISTER',
style: TextStyle(
fontSize: 15.0,
fontWeight: FontWeight.bold,
color: defaultColor,
),
),
),
],
),
],
),
),
),
),
);
},
);
}
}
finally this is my login model
class LoginModel {
bool? status;
String? message;
LoginData? data;
LoginModel.fromJson(Map<String, dynamic> json) {
status = json['status'];
message = json['message'];
data = LoginData.fromJson(json['data']);
}
}
class LoginData {
int? id;
String? name;
String? email;
String? phone;
String? image;
String? token;
LoginData.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
email = json['email'];
phone = json['phone'];
image = json['image'];
token = json['token'];
}
}
Also , I do not know it is the reason or not when I click restart this one shows to me after add firebase to my app but i did not use it just initialized it
Restarted application in 3,811ms.
W/DynamiteModule(14025): Local module descriptor class for com.google.android.gms.providerinstaller.dynamite not found.
I/DynamiteModule(14025): Considering local module com.google.android.gms.providerinstaller.dynamite:0 and remote module com.google.android.gms.providerinstaller.dynamite:0
W/ProviderInstaller(14025): Failed to load providerinstaller module: No acceptable module com.google.android.gms.providerinstaller.dynamite found. Local version is 0 and remote version is 0.
W/ConnectivityManager.CallbackHandler(14025): callback not found for CALLBACK_AVAILABLE message

flutter: Store response json value in variable and put on home page page

how to store my response json value in variable and put on home page page.
How to store the response data coming in the console into a variable and take that store data to the homepage.
I want to store sid, uid, user_name and user_email and show it on home page
This is my auth.dart
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:login_and_signup/Utils/api.dart';
import 'package:login_and_signup/Utils/http_exception.dart';
class Auth with ChangeNotifier {
var MainUrl = Api.authUrl;
Future<void> Authentication(String user_name, String user_email,
String mobile_no, String password, String action) async {
try {
// var url = Uri.parse('${MainUrl}/accounts:${endpoint}?key=${AuthKey}');
var url = Uri.parse('$MainUrl&action=$action');
print(url);
if (action == 'registration') {
Map<String, dynamic> body = {
"user_name": user_name,
'user_email': user_email,
"mobile_no": mobile_no,
"password": password,
};
final responce = await http.post(url,
headers: {"Accept": "Application/json"}, body: (body));
print("Response" + responce.body);
final responceData = json.decode(responce.body);
print("responceData" + responceData.toString());
} else {
Map<String, dynamic> body = {
"user_name": user_name,
'user_email': user_email,
"username": mobile_no,
"password": password,
};
final responce = await http.post(url,
headers: {"Accept": "Application/json"}, body: (body));
print("Response" + responce.body);
final responceData = json.decode(responce.body);
print("responceData" + responceData.toString());
if (responceData['sid'] == null) {
print('seggv');
throw HttpException(responceData['msg']);
} else if (responceData['status'] == true) {}
// notifyListeners();
}
notifyListeners();
} catch (e) {
throw e;
}
}
Future<void> login(
String user_name, String user_email, String mobile_no, String password) {
return Authentication(user_name, user_email, mobile_no, password, 'login');
}
Future<void> signUp(
String user_name, String user_email, String mobile_no, String password) {
return Authentication(
user_name, user_email, mobile_no, password, 'registration');
}
}
This is my login.dart
// import 'package:flutter/material.dart';
// import 'package:login_signup_with_api/Providers/auth.dart';
// import 'package:login_signup_with_api/Screens/signup.dart';
// import 'package:login_signup_with_api/Utils/http_exception.dart';
import 'package:flutter/material.dart';
import 'package:login_and_signup/Providers/auth.dart';
import 'package:login_and_signup/Providers/auth.dart';
import 'package:login_and_signup/Providers/auth2.dart';
import 'package:login_and_signup/Screens/home_screen.dart';
import 'package:login_and_signup/Screens/home_screen2.dart';
// import 'package:login_and_signup/Providers/login_auth.dart';
import 'package:login_and_signup/Screens/signup.dart';
import 'package:login_and_signup/Utils/http_exception.dart';
import 'package:provider/provider.dart';
class LoginScreen extends StatefulWidget {
String routeName = "/login";
#override
_LoginScreenState createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
final GlobalKey<FormState> _formKey = GlobalKey();
TextEditingController _mobileController = new TextEditingController();
TextEditingController _passwordController = new TextEditingController();
Map<String, String> _authData = {
'user_name': '',
'user_email': '',
'username': '',
'password': ''
};
Future _submit() async {
print('aa' + _authData['username']!);
if (!_formKey.currentState!.validate()) {
//invalid
return;
}
_formKey.currentState!.save();
try {
await Provider.of<Auth>(context, listen: false)
.login(_authData['user_name']!, _authData['user_email']!,
_authData['username']!, _authData['password']!)
.then((_) {
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (context) => HomeScreen()));
});
print('aaaa' + _authData['username']!);
print('bbbb' + _authData['password']!);
} on HttpException catch (e) {
// } catch (e) {
var errorMessage = 'Authentication Failed';
if (e.toString().contains('Entered wrong mobile number!')) {
errorMessage = 'Entered wrong mobile number!';
print(errorMessage);
_showerrorDialog(errorMessage);
} else if (e.toString().contains('Entered wrong password!')) {
errorMessage = 'Entered wrong password!';
_showerrorDialog(errorMessage);
}
} catch (error) {
var errorMessage = 'Please try again later';
_showerrorDialog(errorMessage);
}
}
#override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
// backgroundColor: Colors.white,
body: SingleChildScrollView(
child: Container(
child: Stack(
children: <Widget>[
Container(
height: MediaQuery.of(context).size.height * 0.65,
width: MediaQuery.of(context).size.width * 0.85,
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
topRight: Radius.circular(360),
bottomRight: Radius.circular(360)),
color: Colors.blue),
),
Container(
padding:
EdgeInsets.only(top: 50, left: 20, right: 20, bottom: 50),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Sign In",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 40),
),
SizedBox(
height: 10,
),
Text(
"Sign in with your username or email",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 10),
),
Form(
key: _formKey,
child: Container(
padding: EdgeInsets.only(top: 50, left: 20, right: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"username",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 12),
),
TextFormField(
// obscureText: true,
// controller: _mobileController,
style: TextStyle(color: Colors.white),
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white),
),
prefixIcon: Icon(
Icons.vpn_key,
color: Colors.white,
)),
validator: (value) {
if (value!.isEmpty || value.length < 1) {
return 'valid no';
}
},
onSaved: (value) {
_authData['username'] = value!;
},
),
SizedBox(
height: 10,
),
SizedBox(
height: 10,
),
Text(
"Password",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 12),
),
TextFormField(
// controller: _passwordController,
obscureText: true,
style: TextStyle(color: Colors.white),
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white),
),
prefixIcon: Icon(
Icons.vpn_key,
color: Colors.white,
)),
validator: (value) {
if (value!.isEmpty || value.length < 5) {
return 'Password is to Short';
}
},
onSaved: (value) {
_authData['password'] = value!;
},
),
Container(
padding: EdgeInsets.only(top: 40),
width: 140,
child: RaisedButton(
onPressed: () {
print(_authData['username']);
print(_authData['password']);
_submit();
},
shape: RoundedRectangleBorder(
borderRadius:
new BorderRadius.circular(10.0),
),
child: Text(
'Sign In',
style: TextStyle(color: Colors.white),
),
color: Colors.green),
),
Align(
alignment: Alignment.bottomRight,
child: InkWell(
onTap: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (ctx) => SignUpScreen()));
},
child: Container(
padding: EdgeInsets.only(top: 90),
child: Text(
"Create Account",
style: TextStyle(
decoration: TextDecoration.underline,
color: Colors.blue,
fontSize: 16),
),
),
),
)
],
),
),
),
],
),
),
],
),
),
),
);
}
void _showerrorDialog(String message) {
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: Text(
'An Error Occurs',
style: TextStyle(color: Colors.blue),
),
content: Text(message),
actions: <Widget>[
FlatButton(
child: Text('Okay'),
onPressed: () {
Navigator.of(context).pop();
},
)
],
),
);
}
}
You can use Shared Preference to store and retrieve user info anywhere in app.
Please check below plugin for more details :
https://pub.dev/packages/shared_preferences

When FirebaseAuth instance is initiated it gives error on Flutter form

This is my first Flutter project and I'm confused about something. I have created this form, and whenever I initiate a Firebase instance the form disappears.
If I remove this code final FirebaseAuth _firebaseAuth = FirebaseAuth.instance; it works fine, the form will display but if uncommented the form disappears and return this error:
Null check operator used on a null value
Code:
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'dart:core';
import 'package:email_validator/email_validator.dart';
class CreateLogin extends StatefulWidget {
final Function goToHomePage;
CreateLogin({this.goToHomePage});
#override
_CreateLoginState createState() => _CreateLoginState();
}
class _CreateLoginState extends State<CreateLogin> {
bool _termsAgreed = false;
String email, password, confirmPassword;
bool saveAttempted = false;
final formKey = GlobalKey<FormState>();
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
void _createUser({String email, String password}) {
_firebaseAuth.createUserWithEmailAndPassword(email: email, password: password).then((authResult) {
print(authResult.user);
}).catchError((error){
print(error);
});
}
#override
Widget build(BuildContext context) {
return Form(
key: formKey,
child: Container(
child: Column(
children: <Widget>[
Text('SIGN UP', style: TextStyle(color: Colors.white, fontWeight: FontWeight.w600, fontSize: 26.0),),
SizedBox(height: 5,),
TextFormField( autovalidate: saveAttempted, autovalidateMode: AutovalidateMode.always, validator: (emailValue) {
if(emailValue.isEmpty){
return "This email field cannot be empty";
}return null;
},
onChanged: (textVlaue) {
setState(() {
email = textVlaue;
});
},
decoration: InputDecoration(errorStyle: TextStyle(color: Colors.white), hintText: 'Enter Email', hintStyle: TextStyle(color: Colors.white.withOpacity(0.6)), border: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white),
)), style: TextStyle(fontSize: 22, color: Colors.white),),
SizedBox(height: 5,),
TextFormField( autovalidate: saveAttempted, validator: (password) {
if(password.isEmpty){
return "This email field cannot be empty";
} if(password.length < 8){
return "Password must be greater han 8 character";
} if(EmailValidator.validate(email) != true){
return "Invalid email";
}return null;
},
onChanged: (textVlaue) {
setState(() {
password = textVlaue;
});
},
obscureText: true,
decoration: InputDecoration(errorStyle: TextStyle(color: Colors.white), hintText: 'Enter Password', hintStyle: TextStyle(color: Colors.white.withOpacity(0.6)), border: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white),
)), style: TextStyle(fontSize: 22, color: Colors.white),),
SizedBox(height: 5,),
TextFormField( autovalidate: saveAttempted, validator: (confirmPassword) {
if(confirmPassword.isEmpty){
return "This email field cannot be empty";
} if (confirmPassword != password) {
return "It must match password";
} return null;
},
onChanged: (textVlaue) {
setState(() {
confirmPassword = textVlaue;
});
},
obscureText: true,
decoration: InputDecoration(errorStyle: TextStyle(color: Colors.white), hintText: 'Comfirm Password', hintStyle: TextStyle(color: Colors.white.withOpacity(0.6)), border: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white),
)), style: TextStyle(fontSize: 22, color: Colors.white),),
SizedBox(height: 5,),
Row(
children: <Widget>[Checkbox(activeColor: Colors.orange, value: _termsAgreed, onChanged: (newValue) {
setState(() {
_termsAgreed = newValue;
});
},), Text('Terms & Conditions', style: TextStyle(color: Colors.white, fontSize: 16.0),)],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
InkWell( onTap: (){ widget.goToHomePage(); },
child: Text('CANCEL', style: TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold),)),
SizedBox(width: 38,),
InkWell(
onTap: () {
setState(() {
saveAttempted = true;
});
if(formKey.currentState.validate()) {
formKey.currentState.save();
// _createUser(email: email, password: password);
}
},
child: Container(
padding: EdgeInsets.symmetric(vertical: 16.0, horizontal: 34.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(30.0),
),
child: Text('SAVE', style: TextStyle(color: Colors.red, fontSize: 20, fontWeight: FontWeight.bold),)),
),
],
),
Text('Agree to Terms & Conditions', style: TextStyle(color: Colors.white, fontSize: 12),),
],
),
),
);
}
}
Check that you have correctly initialized firebase in your project
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}