Related
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
When I try to use final firebaseUser = context.watch<User?>(), the value of firebaseUser is always null when I try to hot restart the application. And the after login IN (Email verified User) to application, the adminScreen is not build. I have used StreamProvider.
Main.dart
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:heath_matthews_physio/screens/LogoutScreen.dart';
import 'package:heath_matthews_physio/screens/excercise.dart';
import 'package:heath_matthews_physio/screens/programsMy.dart';
import 'package:heath_matthews_physio/screens/AdminScreen.dart';
import 'package:heath_matthews_physio/screens/excerciseScreen.dart';
import 'package:heath_matthews_physio/screens/information_screen.dart';
import 'package:heath_matthews_physio/screens/login.dart';
import 'package:heath_matthews_physio/screens/mainScreen2.dart';
import 'package:heath_matthews_physio/screens/main_screen.dart';
import 'package:heath_matthews_physio/screens/myPrograms.dart';
import 'package:heath_matthews_physio/screens/reg_name_and_dp.dart';
import 'package:heath_matthews_physio/screens/register.dart';
import 'package:heath_matthews_physio/screens/verificationPage.dart';
import 'package:heath_matthews_physio/screens/workout-page.dart';
import 'package:heath_matthews_physio/screens/workoutScreen.dart';
import 'package:heath_matthews_physio/services/firebase_auth_methods.dart';
import 'package:heath_matthews_physio/wrapper.dart';
import 'package:provider/provider.dart';
import 'firebase_options.dart';
import 'screens/splash_screen.dart';
import 'package:firebase_core/firebase_core.dart';
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
runApp(
MaterialApp(
home: MyApp(),
debugShowCheckedModeBanner: false,
),
);
}
final navigatorKey = GlobalKey<NavigatorState>();
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
Provider<FirebaseAuthMethods>(
create: (_) => FirebaseAuthMethods(FirebaseAuth.instance),
),
StreamProvider(
create: (context) => context.read<FirebaseAuthMethods>().authState,
initialData: Null,
),
],
child: GetMaterialApp(
navigatorKey: navigatorKey,
debugShowCheckedModeBanner: false,
initialRoute: '/',
routes: {
// When navigating to the "/" route, build the FirstScreen widget.
'/': (context) => const Splash(),
// When navigating to the "/second" route, build the SecondScreen widget.
'/wrapper': (context) => wrapper(),
'/mainScreen': (context) => const mainScreen(),
'/mainScreen2': (context) => const mainScreen2(),
'/loginScreen': (context) => const Login(),
'/registerScreen': (context) => const Register(),
'/informationScreen': (context) => const informationScreen(),
'/mainScreen2': (context) => const mainScreen2(),
'/reg_name_and_dp': (context) => reg_name_and_dp(),
'/myPrograms': (context) => const myPrograms(),
'/adminScreen': (context) => adminScreen(),
'/program': (context) => program(),
'/workout-page': (context) => workoutScreen(),
// '/exerciseScreen':(context)=>excerciseScreen(),
'/exercise': (context) => exercise(),
'/workoutScreen': (context) => workoutScreen1(),
'/logout': (context) => logoutScreen(),
'/verification': (context) => verificationPage(),
},
theme: ThemeData(
primarySwatch: Colors.blue,
accentColor: Color(0xFF193669),
),
),
);
}
}
splash_screen.dart
import 'package:flutter/material.dart';
import 'package:heath_matthews_physio/DynamicSize/size.dart';
class Splash extends StatefulWidget {
const Splash({Key? key}) : super(key: key);
#override
_SplashState createState() => _SplashState();
}
class _SplashState extends State<Splash> {
#override
void initState() {
super.initState();
_navigateTologin();
}
_navigateTologin() async {
await Future.delayed(Duration(milliseconds: 1500), () {});
// Navigator.pushReplacementNamed(context, '/mainScreen');
Navigator.pushReplacementNamed(context, '/wrapper');
}
#override
Widget build(BuildContext context) {
return Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Color.fromARGB(178, 25, 54, 105),
Colors.white,
Color(0xFFEDC152)
])),
child: Padding(
padding: EdgeInsets.all(DynamicSize.Aaheight(78.0)),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Image.asset("images/HMP LOGO.png"),
],
),
),
);
}
}
wrapper.dart
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'screens/AdminScreen.dart';
import 'screens/main_screen.dart';
class wrapper extends StatelessWidget {
const wrapper({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
final firebaseUser = context.watch<User?>();
print("User : ${firebaseUser}"); //This always print null
if (firebaseUser != null) {
return adminScreen();
} else {
return mainScreen();
}
}
}
firebase_auth_methods.dart
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:heath_matthews_physio/screens/register.dart';
class FirebaseAuthMethods {
final FirebaseAuth _auth;
FirebaseAuthMethods(this._auth);
//State Management
Stream<User?> get authState => _auth.idTokenChanges();
//Email Sign Up Function
Future<void> singUpWithEmail({
required String email,
required String password,
required BuildContext context,
}) async {
try {
await _auth.createUserWithEmailAndPassword(
email: email, password: password);
await sendVerification(context);
} on FirebaseAuthException catch (e) {
print(e.message);
}
}
//Email LogIn Function
Future<void> signInWithEmail(
{required String email,
required String password,
required BuildContext context}) async {
try {
await _auth.signInWithEmailAndPassword(email: email, password: password);
if (!_auth.currentUser!.emailVerified) {
await sendVerification(context);
}
} on FirebaseAuthException catch (e) {
print(e.message);
}
}
//Send Email Verification
Future<void> sendVerification(BuildContext context) async {
try {
_auth.currentUser!.sendEmailVerification();
popUpVerificationMsg(context);
} on FirebaseAuthException catch (e) {
print(e.message);
}
}
}
login.dart
import 'package:flutter/material.dart';
// import 'package:dotted_line/dotted_line.dart';
import 'package:heath_matthews_physio/DynamicSize/size.dart';
import 'package:heath_matthews_physio/services/firebase_auth_methods.dart';
import 'package:provider/provider.dart';
class Login extends StatefulWidget {
const Login({Key? key}) : super(key: key);
#override
State<Login> createState() => _LoginState();
}
class _LoginState extends State<Login> {
final emailController = TextEditingController();
final passwordController = TextEditingController();
#override
void dispose() {
emailController.dispose();
passwordController.dispose();
super.dispose();
}
//To Control PassWord Visibiltiy
late bool _visibility;
Future popUpConfirm(BuildContext context) {
return showDialog(
context: context,
builder: (BuildContext context) {
return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(DynamicSize.Faheight(16))),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: EdgeInsets.only(
left: DynamicSize.Fawidth(31),
top: DynamicSize.Faheight(24),
right: DynamicSize.Fawidth(31)),
child: Image.asset('images/EmailSent.png'),
),
//Msg
SizedBox(height: DynamicSize.Faheight(24)),
Padding(
padding: EdgeInsets.only(
left: DynamicSize.Fawidth(16),
right: DynamicSize.Fawidth(16),
bottom: DynamicSize.Faheight(32)),
child: Text(
"You will receive an email with intructions on how to reset your password in a few minutes.\n\nNote : Don't forget to check your spam mail box.\n\nThank you :)",
style: TextStyle(
fontFamily: 'DMSans',
fontSize: DynamicSize.Faheight(16),
fontWeight: FontWeight.w400,
letterSpacing: DynamicSize.Fawidth(0.5),
color: Color(0xFF193669),
fontStyle: FontStyle.normal,
),
),
)
],
),
);
},
);
}
Future popUpDialog(BuildContext context) {
return showDialog(
context: context,
builder: (BuildContext context) {
return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(DynamicSize.Faheight(16))),
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: EdgeInsets.only(
left: DynamicSize.Fawidth(31),
top: DynamicSize.Faheight(16),
right: DynamicSize.Fawidth(31)),
child: Image.asset('images/Illustration-forgot-password.png'),
),
//Forgot password Text
SizedBox(height: DynamicSize.Faheight(24)),
Padding(
padding: EdgeInsets.only(left: DynamicSize.Fawidth(24)),
child: Align(
alignment: Alignment.centerLeft,
child: Text(
'Forgot your password?',
style: TextStyle(
fontStyle: FontStyle.normal,
color: Color(0xFF193669),
fontFamily: 'DMSans',
fontSize: DynamicSize.Faheight(16),
fontWeight: FontWeight.w500,
letterSpacing: DynamicSize.Fawidth(1),
),
),
),
),
//Email Text
SizedBox(height: DynamicSize.Faheight(36)),
Padding(
padding: EdgeInsets.only(left: DynamicSize.Fawidth(24)),
child: Align(
alignment: Alignment.centerLeft,
child: Text(
'Email',
style: TextStyle(
fontStyle: FontStyle.normal,
color: Color(0xFF193669),
fontFamily: 'DMSans',
fontSize: DynamicSize.Faheight(12),
fontWeight: FontWeight.w700,
letterSpacing: DynamicSize.Fawidth(1),
),
),
),
),
//Email TextField
SizedBox(height: DynamicSize.Faheight(9)),
Padding(
padding:
EdgeInsets.symmetric(horizontal: DynamicSize.Fawidth(24)),
child: TextField(
decoration: InputDecoration(
hintText: 'Email address',
hintStyle: TextStyle(
color: Color(0xFF636363),
),
focusedBorder: new UnderlineInputBorder(
borderSide: BorderSide(color: Color(0xFF193669)),
),
),
keyboardType: TextInputType.emailAddress,
),
),
//Button
SizedBox(height: DynamicSize.Faheight(24)),
Padding(
padding:
EdgeInsets.symmetric(horizontal: DynamicSize.Fawidth(24)),
child: SizedBox(
width: double.infinity,
height: DynamicSize.Faheight(39),
child: OutlinedButton(
onPressed: () {
Navigator.pop(context);
popUpConfirm(context);
},
style: OutlinedButton.styleFrom(
side: BorderSide(
color: Color(0xFF193669),
),
backgroundColor: Color(0xFFF0F2F4),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(
DynamicSize.Faheight(15))),
),
child: Text(
'Send me reset password instructions',
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'DMSans',
fontStyle: FontStyle.normal,
fontWeight: FontWeight.w500,
fontSize: DynamicSize.Faheight(11),
letterSpacing: DynamicSize.Fawidth(0.8),
color: Color(0xFF193669),
),
),
),
),
),
SizedBox(height: DynamicSize.Faheight(30)),
],
),
),
);
},
);
}
#override
void initState() {
super.initState();
_visibility = false;
}
void LoginUser() {
context.read<FirebaseAuthMethods>().signInWithEmail(
email: emailController.text.trim(),
password: passwordController.text.trim(),
context: context);
}
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
body: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
//Grettings
SizedBox(height: DynamicSize.Faheight(150)),
Container(
child: Text(
"Welcome Back",
style: TextStyle(
fontFamily: 'DMSams',
fontSize: DynamicSize.Faheight(30),
fontWeight: FontWeight.w700,
color: Color(0xff193669),
letterSpacing: DynamicSize.Fawidth(0.5),
),
),
),
SizedBox(height: DynamicSize.Faheight(17)),
Container(
margin: EdgeInsets.symmetric(horizontal: DynamicSize.Fawidth(17)),
child: Text(
'Hey, nice seeing you again !! Please login/register to continue further',
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'DMSans',
fontSize: DynamicSize.Faheight(14),
fontWeight: FontWeight.w600,
color: Color(0xff193669),
letterSpacing: DynamicSize.Fawidth(0.5),
),
),
),
//User Credentials
SizedBox(height: DynamicSize.Faheight(60)),
Container(
padding: EdgeInsets.symmetric(horizontal: DynamicSize.Fawidth(19)),
margin: EdgeInsets.symmetric(horizontal: DynamicSize.Fawidth(25)),
alignment: Alignment.center,
height: DynamicSize.Faheight(50),
decoration: BoxDecoration(
color: Color(0xFFF3F3F3),
borderRadius: BorderRadius.circular(DynamicSize.Faheight(15)),
boxShadow: [
BoxShadow(
offset: Offset(0, DynamicSize.Faheight(2)),
color: Color.fromARGB(141, 0, 0, 0),
blurRadius: DynamicSize.Faheight(3),
),
BoxShadow(
offset: Offset(DynamicSize.Fawidth(-2), 0),
color: Color(0xFFF3F3F3),
blurRadius: DynamicSize.Faheight(1),
),
BoxShadow(
offset: Offset(DynamicSize.Fawidth(2), 0),
color: Color(0xFFF3F3F3),
blurRadius: DynamicSize.Faheight(1),
),
],
),
child: TextField(
controller: emailController,
style: TextStyle(
fontFamily: 'DMSams',
fontSize: DynamicSize.Faheight(14),
letterSpacing: DynamicSize.Fawidth(0),
),
decoration: InputDecoration(
hintText: "Email address",
border: InputBorder.none,
),
keyboardType: TextInputType.emailAddress,
),
),
//Password field
SizedBox(height: DynamicSize.Faheight(15)),
Container(
padding: EdgeInsets.only(
left: DynamicSize.Fawidth(19), right: DynamicSize.Fawidth(8)),
margin: EdgeInsets.symmetric(horizontal: DynamicSize.Fawidth(25)),
alignment: Alignment.center,
height: DynamicSize.Faheight(50),
decoration: BoxDecoration(
color: Color(0xFFF3F3F3),
borderRadius: BorderRadius.circular(DynamicSize.Faheight(15)),
boxShadow: [
BoxShadow(
offset: Offset(0, DynamicSize.Faheight(2)),
color: Color.fromARGB(141, 0, 0, 0),
blurRadius: DynamicSize.Faheight(3),
),
BoxShadow(
offset: Offset(DynamicSize.Fawidth(-2), 0),
color: Color(0xFFF3F3F3),
blurRadius: DynamicSize.Faheight(1),
),
BoxShadow(
offset: Offset(DynamicSize.Fawidth(2), 0),
color: Color(0xFFF3F3F3),
blurRadius: DynamicSize.Faheight(1),
),
],
),
child: TextField(
controller: passwordController,
textAlignVertical: TextAlignVertical.center,
style: TextStyle(
fontFamily: 'DMSams',
fontSize: DynamicSize.Faheight(14),
letterSpacing: DynamicSize.Fawidth(0),
),
decoration: InputDecoration(
hintText: "Password",
border: InputBorder.none,
suffixIcon: IconButton(
splashRadius: 1,
splashColor: Colors.transparent,
icon: Icon(
_visibility ? Icons.visibility_off : Icons.visibility),
color: Color(_visibility ? (0xFF193669) : (0xFF666161)),
onPressed: () => setState(() => _visibility = !_visibility),
),
),
obscureText: !_visibility,
),
),
//Forgot Password Button
SizedBox(height: DynamicSize.Faheight(13)),
Container(
padding: EdgeInsets.only(right: DynamicSize.Fawidth(36)),
alignment: Alignment.topRight,
child: GestureDetector(
onTap: () => popUpDialog(context),
child: Text(
"Forgot Password ?",
style: TextStyle(
fontFamily: "DMSans",
fontSize: DynamicSize.Faheight(15),
color: Color(0xFF193669),
),
),
),
),
//Sign In Button
SizedBox(height: DynamicSize.Faheight(40)),
Padding(
padding: EdgeInsets.symmetric(horizontal: DynamicSize.Fawidth(15)),
child: SizedBox(
width: double.infinity,
height: DynamicSize.Faheight(50),
child: TextButton(
onPressed: LoginUser,
// Navigator.pushNamedAndRemoveUntil(
// context, '/adminScreen', (route) => false),
style: TextButton.styleFrom(
backgroundColor: Color(0xFF193669),
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(DynamicSize.Faheight(15)),
)
// padding: EdgeInsets.symmetric(horizontal: 1),
),
child: Text(
'SIGN IN',
style: TextStyle(
fontFamily: 'DMSans',
fontSize: DynamicSize.Faheight(15),
letterSpacing: DynamicSize.Fawidth(0.5),
color: Colors.white,
),
),
),
),
),
//Register Button
SizedBox(height: DynamicSize.Faheight(16)),
Padding(
padding: EdgeInsets.symmetric(horizontal: DynamicSize.Fawidth(15)),
child: SizedBox(
width: double.infinity,
height: DynamicSize.Faheight(50),
child: TextButton(
onPressed: () =>
Navigator.pushNamed(context, '/registerScreen'),
style: TextButton.styleFrom(
backgroundColor: Color(0xFF193669),
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(DynamicSize.Faheight(15)),
)
// padding: EdgeInsets.symmetric(horizontal: 1),
),
child: Text(
'REGISTER',
style: TextStyle(
fontFamily: 'DMSans',
fontSize: DynamicSize.Faheight(15),
letterSpacing: DynamicSize.Fawidth(0.5),
color: Colors.white,
),
),
),
),
),
// Row(
// children: [
// Text("No Account?",style: GoogleFonts.dmSans(
// fontSize: 12.0,
// color: Color(0xFF2F3F70)
// ),),
// Text("Sign Up",style: TextStyle(
// fontSize:12.0,
// fontWeight: FontWeight.w500,
// decoration: TextDecoration.underline,
// fontFamily: 'dmSams'
// ),
// )
// ],
// )
],
),
);
}
}
How can I add an admin page to the existing pages?
I just want one default admin to enter which will only display users from Firebase. I would like a specific email and password to be given which will allow access for that one admin.
I'm attaching the login page
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'startuppage.dart';
class MyLogin extends StatefulWidget {
const MyLogin({Key? key}) : super(key: key);
#override
State<MyLogin> createState() => _MyLoginState();
}
class _MyLoginState extends State<MyLogin> {
//editing controller
final TextEditingController emailController = TextEditingController();
final TextEditingController passwordController = TextEditingController();
int _success = 1 ;
late String _userEmail = "";
final user = FirebaseAuth.instance.currentUser;
Future SignIn() async {
await FirebaseAuth.instance.signInWithEmailAndPassword(
email: emailController.text.trim(),
password: passwordController.text.trim()
);
}
#override
Widget build(BuildContext context) {
return Container(
decoration: const BoxDecoration(
//color: Color(0xFFaac8ba),
gradient: LinearGradient
(begin: Alignment.bottomLeft,
end: Alignment.bottomRight,
colors: [
Color(0xFFde6262),
Color(0xFFffb88c)
]
),
),
child : Scaffold(
backgroundColor: Colors.transparent, //By default, in scaffold the bg color is white.
body: Container(
padding: const EdgeInsets.only(top: 130, left: 35, right: 0),
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
"Welcome Back\nTo Check-it.",
style: TextStyle(
color: Colors.black,
fontSize: 30,
fontFamily: 'Montserrat',
letterSpacing: 3,
fontWeight: FontWeight.bold,
),
),
const SizedBox(
height: 50.0,
),
TextField(
controller: emailController,
keyboardType: TextInputType.emailAddress,
decoration: const InputDecoration(
hintText: "Email",
prefixIcon: Icon(Icons.mail, color: Colors.black,)
),
),
const SizedBox(
height: 20.0,
),
TextField(
controller:passwordController,
obscureText: true,
keyboardType: TextInputType.visiblePassword,
decoration: const InputDecoration(
hintText: "Password",
prefixIcon: Icon(Icons.lock, color: Colors.black,)
),
),
const SizedBox(
height: 50.0,
),
ElevatedButton(
onPressed: () async{
// _signIn();
SignIn();
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const Imageslider()),
);
},
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all<Color>(Colors.black12),
),
child: const Text("Login",
style: TextStyle(
fontSize: 18,
color: Colors.black54),
),
),
const SizedBox(
height: 10.0,
),
Container(
alignment: Alignment.bottomCenter,
child: Text(
_success == 1
?''
: (
_success == 2
? 'Sign-in successful! '
: 'Sign-in failed!'),
style: const TextStyle(
color: Colors.white70,
)
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextButton(
onPressed: () {
Navigator.pushNamed(context,'signup');
},
child: const Text ('New User? Sign Up',
style : TextStyle(
decoration: TextDecoration.underline,
fontSize: 18,
color: Colors.black45,
),
)),
],
),
],
),
),
),
),
);
}
}
Sign Up Page Code :
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'login.dart';
import 'startuppage.dart';
final FirebaseAuth _auth = FirebaseAuth.instance;
class Mysignup extends StatefulWidget {
const Mysignup({Key? key}) : super(key: key);
#override
State<Mysignup> createState() => _MysignupState();
}
class _MysignupState extends State<Mysignup> {
Future<FirebaseApp> _initializeFirebase() async {
FirebaseApp firebaseApp = await Firebase.initializeApp();
return firebaseApp;
}
//editing controller
final TextEditingController name = TextEditingController();
final TextEditingController emailController = TextEditingController();
final TextEditingController passwordController = TextEditingController();
late bool _success;
bool isLoading = false;
Future<User?> _register(String name, String email, String password) async{
FirebaseAuth _auth = FirebaseAuth.instance;
FirebaseFirestore _firestore = FirebaseFirestore.instance;
try {
UserCredential userCrendetial = await _auth.createUserWithEmailAndPassword(email: emailController.text, password: passwordController.text);
print("Account created Succesfull");
userCrendetial.user?.updateDisplayName(name);
await _firestore.collection('users').doc(_auth.currentUser?.uid).set({
"name": name,
"email": email,
"uid": _auth.currentUser?.uid,
});
return userCrendetial.user;
} catch (e) {
print(e);
return null;
}
}
#override
Widget build(BuildContext context) {
return Container(
decoration: const BoxDecoration(
gradient: LinearGradient
(colors: [
Color(0xFF02aab0),
Color(0xFF00cdac)
],
),
),
child : Scaffold(
backgroundColor: Colors.transparent, //By default, in scaffold the bg color is white.
body: Container(
padding: const EdgeInsets.only(top: 150, left: 35, right: 35),
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
"Let's Create Together.",
style: TextStyle(
color: Colors.black,
fontSize: 30,
letterSpacing: 3,
fontWeight: FontWeight.bold,
),
),
const SizedBox(
height: 40.0,
),
TextField(
controller:name,
keyboardType: TextInputType.name,
decoration: const InputDecoration(
hintText: "Name",
prefixIcon: Icon(Icons.account_circle_rounded, color: Colors.black,)
),
),
const SizedBox(
height: 20.0,
),
TextField(
controller:emailController,
keyboardType: TextInputType.emailAddress,
decoration: const InputDecoration(
hintText: "Email",
prefixIcon: Icon(Icons.mail, color: Colors.black,)
),
),
const SizedBox(
height: 20.0,
),
TextField(
controller:passwordController,
obscureText: true,
keyboardType: TextInputType.visiblePassword,
decoration: const InputDecoration(
hintText: "Password",
prefixIcon: Icon(Icons.lock, color: Colors.black,)
),
),
const SizedBox(
height: 80.0,
),
ElevatedButton(
onPressed: () async{
if (name.text.isNotEmpty &&
emailController.text.isNotEmpty &&
passwordController.text.isNotEmpty) {
setState(() {
isLoading = true;
});
_register(name.text, emailController.text, passwordController.text).then((user) {
if (user == null) {
setState(() {
isLoading = false;
});
Navigator.push(
context, MaterialPageRoute(builder: (_) => MyLogin()));
print("Account Created Sucessful");
} else {
print("Login Failed");
setState(() {
isLoading = false;
});
}
});
} else {
print("Please enter all the fields");
}
},
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all<Color>(Colors.black12),
),
child: const Text("Sign Up",
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
color: Colors.black54),
),
),
],
),
),
),
),
);
}
}
I'm a beginner in FLutter. Please help. Thanks in advance!
You'll want to use StreamBuilder to respond to the FirebaseAuth.instance.authStateChanges() stream that is shown in the first snippet on getting the current user, then detect whether it is the admin user who signed in based on their UID, and then show them the admin page of your UI.
Something like:
child: StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, userSnapshot) {
if (userSnapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
}
if (userSnapshot.connectionState == ConnectionState.done) {
if (!userSnapshot.hasData) {
// TODO: return screen where they sign in
}
else if (userSnapshot.data!.uid == "uidOfYourAdminUser") {
// TODO: return admin screen
}else{
// TODO: return screen for regular signed in user
}
}
}
)
Im new to flutter and currently work as an intern in a small company, I'm trying to get API from laravel and try to login in flutter. Is there anyone can assist me to have a look on my code? I will write them below.
I'm trying to test it without token, but on online tutorial everyone is having token.
api.dart
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
class Network{
final String _url = 'http://192.168.0.138:8000/api/';
var token;
_getToken() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
token = jsonDecode(localStorage.getString('token'))['token'];
}
authData(data, apiUrl) async {
var fullUrl = _url + apiUrl;
return await http.post(
fullUrl,
body: jsonEncode(data),
headers: _setHeaders()
);
}
getData(apiUrl) async {
var fullUrl = _url + apiUrl;
await _getToken();
return await http.get(
fullUrl,
headers: _setHeaders()
);
}
_setHeaders() => {
'Content-type' : 'application/json',
'Accept' : 'application/json',
'Authorization' : 'Bearer $token'
};
}
Login_Screen
import 'package:ezymember/screens/home_screen.dart';
import 'package:ezymember/screens/register_screen.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:ezymember/network_utils/api.dart';
import 'package:shared_preferences/shared_preferences.dart';
class LoginScreen extends StatefulWidget {
const LoginScreen({Key key}) : super(key: key);
#override
_LoginScreenState createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
bool _isLoading = false;
final _formKey = GlobalKey<FormState>();
var member_email;
var member_password;
final _scaffoldKey = GlobalKey<ScaffoldState>();
_showMsg(msg) {
final snackBar = SnackBar(
content: Text(msg),
action: SnackBarAction(
label: 'Close',
onPressed: () {
// Some code to undo the change!
},
),
);
_scaffoldKey.currentState.showSnackBar(snackBar);
}
#override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Stack(
children: <Widget>[
Container(
padding: const EdgeInsets.fromLTRB(15.0, 110.0, 0.0, 0.0),
child: const Text('Hello',
style:
TextStyle(fontSize: 80.0, fontWeight: FontWeight.bold)),
),
Container(
padding: const EdgeInsets.fromLTRB(16.0, 175.0, 0.0, 0.0),
child: const Text('There',
style:
TextStyle(fontSize: 80.0, fontWeight: FontWeight.bold)),
),
Container(
padding: const EdgeInsets.fromLTRB(220.0, 175.0, 0.0, 0.0),
child: const Text('.',
style: TextStyle(
fontSize: 80.0,
fontWeight: FontWeight.bold,
color: Colors.blue)),
)
],
),
Container(
padding: const EdgeInsets.only(top: 35.0, left: 20.0, right: 20.0),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextFormField(
keyboardType: TextInputType.text,
decoration: const InputDecoration(
labelText: 'EMAIL',
labelStyle: TextStyle(
fontFamily: 'Montserrat',
fontWeight: FontWeight.bold,
color: Colors.grey),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.blue)),
),
validator: (emailValue) {
if (emailValue.isEmpty) {
return 'Please enter email';
}
member_email = emailValue;
return null;
},
),
TextFormField(
keyboardType: TextInputType.text,
decoration: const InputDecoration(
labelText: 'PASSWORD',
labelStyle: TextStyle(
fontFamily: 'Montserrat',
fontWeight: FontWeight.bold,
color: Colors.grey),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.blue)),
),
validator: (passwordValue) {
if (passwordValue.isEmpty) {
return 'Please Enter Password';
}
member_password = passwordValue;
return null;
},
),
Padding(
padding: const EdgeInsets.all(10.0),
child: FlatButton(
child: Padding(
padding: const EdgeInsets.only(
top: 8, bottom: 8, left: 10, right: 10),
child: Text(
_isLoading ? 'Proccessing...' : 'Login',
textDirection: TextDirection.ltr,
style: const TextStyle(
color: Colors.white,
fontSize: 20.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
color: Colors.blue,
disabledColor: Colors.grey,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0)),
onPressed: () {
if (_formKey.currentState.validate()) {
_login();
}
},
),
),
],
),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'New to EzyMember ?',
style: TextStyle(fontFamily: 'Montserrat'),
),
const SizedBox(width: 5.0),
InkWell(
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => RegisterPage()));
},
child: const Text(
'Register',
style: TextStyle(
color: Colors.blue,
fontFamily: 'Montserrat',
fontWeight: FontWeight.bold,
decoration: TextDecoration.underline),
),
),
],
),
],
),
),
);
}
void _login() async {
setState(() {
_isLoading = true;
});
var data = {'email': member_email, 'password': member_password};
var res = await Network().authData(data, '/login');
var body = json.decode(res.body);
if (body['success']) {
SharedPreferences localStorage = await SharedPreferences.getInstance();
localStorage.setString('token', json.encode(body['token']));
localStorage.setString('user', json.encode(body['user']));
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const HomeScreen()),
);
} else {
_showMsg(body['message']);
}
setState(() {
_isLoading = false;
});
}
}
I'm getting this error when i make any changes to my app, i need to re run my app to get rid of this error. I tried to make some changes to my navigation but nothing changes. I also i'm searching for hours on the google to find something useful but i can't find anything to make it work.
Note: I'm beginner on Flutter development
Main.dart:
import 'dart:io';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:tasker/screens/HomeScreen.dart';
import 'package:progress_dialog/progress_dialog.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: LoginDemo(),
);
}
}
class LoginDemo extends StatefulWidget {
#override
_LoginDemoState createState() => _LoginDemoState();
}
class _LoginDemoState extends State<LoginDemo> {
late ProgressDialog progressDialog;
FirebaseAuth auth = FirebaseAuth.instance;
String email = "";
String password = "";
#override
Widget build(BuildContext context) {
progressDialog = ProgressDialog(context);
Future<String> getCurrentUserEmail() async {
FirebaseUser user = await auth.currentUser();
String userEmail = user.email.toString();
return userEmail;
}
// Navigate user to HomeScreen if already singed in
if (auth.currentUser() != null) {
Future.delayed(Duration(seconds: 3));
Navigator.pushReplacement(context, new MaterialPageRoute(builder: (context) => HomeScreen(userEmail: '',)));
}
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text("Login"),
),
body: SingleChildScrollView(
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 60.0),
child: Center(
child: Container(
width: 200,
height: 150,
/*
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(50.0)),*/
child: Image(
image: NetworkImage('https://cdn-icons-png.flaticon.com/512/1055/1055672.png'),
)),
),
),
Padding(
padding: const EdgeInsets.only(left:15.0, right: 15.0, top:30, bottom: 0),
//padding: EdgeInsets.symmetric(horizontal: 15),
child: TextField(
onChanged: (value) {
setState(() {
this.email = value;
});
},
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Email',
hintText: 'Enter email'),
),
),
Padding(
padding: const EdgeInsets.only(
left: 15.0, right: 15.0, top: 15, bottom: 0),
//padding: EdgeInsets.symmetric(horizontal: 15),
child: TextField(
onChanged: (value) {
setState(() {
this.password = value;
});
},
obscureText: true,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Password',
hintText: 'Enter password'),
),
),
TextButton(
onPressed: (){
// open reset password screen
},
child: Text(
'Forgot Password?',
style: TextStyle(color: Colors.blue, fontSize: 15),
),
),
Container(
height: 50,
width: 250,
decoration: BoxDecoration(
color: Colors.blue, borderRadius: BorderRadius.circular(20)),
child: TextButton (
onPressed: () async {
progressDialog.show();
try {
AuthResult authResult = await FirebaseAuth.instance.signInWithEmailAndPassword(
email: email.toString(),
password: password.toString()
);
FirebaseUser user = authResult.user;
if (user == null) {
progressDialog.hide();
print("logged in");
await Future.delayed(Duration(seconds: 3));
Navigator.pushReplacement(context, new MaterialPageRoute(builder: (context) => HomeScreen(userEmail: '',)));
}
} catch (e) {
print(e.toString());
}
},
child: Text(
'Login',
style: TextStyle(color: Colors.white, fontSize: 25),
),
),
),
SizedBox(
height: 130,
),
TextButton(
onPressed: (){
// open reset password screen
},
child: Text(
'New user? Sign up!',
style: TextStyle(color: Colors.black, fontSize: 20, fontWeight: FontWeight.bold),
),
),
],
),
),
floatingActionButton: FloatingActionButton(onPressed: () {
},),
floatingActionButtonLocation: FloatingActionButtonLocation.endFloat
);
}
}
I found multiple issues with the code, but the one which caused the debugLocked error was using future directly inside the build method, you either put the future in a FutureBuilder or run outside the build method.
Here is the code fixed:
import 'dart:io';
import 'package:tasker/screens/HomeScreen.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter_progress_dialog/flutter_progress_dialog.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: LoginDemo(),
);
}
}
class LoginDemo extends StatefulWidget {
#override
_LoginDemoState createState() => _LoginDemoState();
}
class _LoginDemoState extends State<LoginDemo> {
late ProgressDialog progressDialog;
FirebaseAuth auth = FirebaseAuth.instance;
String email = "";
String password = "";
Future<String>? getCurrentUserEmail() async {
User user = await auth.currentUser!;
String userEmail = user.email.toString();
return userEmail;
}
// Navigate user to HomeScreen if already singed in
#override
void initState() {
progressDialog = ProgressDialog(
child: Container(
child: Text('Loading'),
),
);
// TODO: implement initState
super.initState();
}
Future<void>? checkUserLoggedIn() async {
if (auth.currentUser != null) {
await Future.delayed(Duration(seconds: 3));
Navigator.pushReplacement(
context,
new MaterialPageRoute(
builder: (context) => HomeScreen(
userEmail: '',
)));
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text("Login"),
),
body: ProgressDialog(
child: SingleChildScrollView(
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 60.0),
child: Center(
child: Container(
width: 200,
height: 150,
child: Image(
image: NetworkImage(
'https://cdn-icons-png.flaticon.com/512/1055/1055672.png'),
)),
),
),
Padding(
padding: const EdgeInsets.only(
left: 15.0, right: 15.0, top: 30, bottom: 0),
//padding: EdgeInsets.symmetric(horizontal: 15),
child: TextField(
onChanged: (value) {
setState(() {
this.email = value;
});
},
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Email',
hintText: 'Enter email'),
),
),
Padding(
padding: const EdgeInsets.only(
left: 15.0, right: 15.0, top: 15, bottom: 0),
//padding: EdgeInsets.symmetric(horizontal: 15),
child: TextField(
onChanged: (value) {
setState(() {
this.password = value;
});
},
obscureText: true,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Password',
hintText: 'Enter password'),
),
),
TextButton(
onPressed: () {
// open reset password screen
},
child: Text(
'Forgot Password?',
style: TextStyle(color: Colors.blue, fontSize: 15),
),
),
Container(
height: 50,
width: 250,
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(20)),
child: TextButton(
onPressed: () async {
showProgressDialog();
try {
UserCredential authResult = await FirebaseAuth.instance
.signInWithEmailAndPassword(
email: email.toString(),
password: password.toString());
User user = authResult.user!;
if (user == null) {
dismissProgressDialog();
print("logged in");
await Future.delayed(Duration(seconds: 3));
Navigator.pushReplacement(
context,
new MaterialPageRoute(
builder: (context) => HomeScreen(
userEmail: '',
)));
}
} catch (e) {
print(e.toString());
}
},
child: Text(
'Login',
style: TextStyle(color: Colors.white, fontSize: 25),
),
),
),
SizedBox(
height: 130,
),
TextButton(
onPressed: () {
// open reset password screen
},
child: Text(
'New user? Sign up!',
style: TextStyle(
color: Colors.black,
fontSize: 20,
fontWeight: FontWeight.bold),
),
),
],
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {},
),
floatingActionButtonLocation: FloatingActionButtonLocation.endFloat);
}
}