I am trying to display current user data from Firebase, and it works totally fine, but when I logout and login with a new email ID, the app also shows previous user data instead of new user login data.
My signIn function in Signin page
class LoginPage extends StatefulWidget {
//when user is login then save their userid and after use this for fetching current user data
//this help in StudentData.dart page
var userId;
@override
State<LoginPage> createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
final emailController = TextEditingController();
final passwordController = TextEditingController();
//for Validation
final _key = GlobalKey<FormState>();
//for geeting input and store email & password
var email = "";
var password = "";
//for Loading Indicator
bool isLodaing = false;
//for login
Future userLogin() async {
//check internet is on or not
final ip = context.read<InternetProvider>();
await ip.checkInternetConnection();
//for checking Internet
if (ip.hasInternet == false) {
openSnackbar(context, "Check your internet connection", Colors.red);
} else {
try {
UserCredential userCredential = await FirebaseAuth.instance
.signInWithEmailAndPassword(email: email, password: password);
//when user loged in that time save user id that help after for fetch data in StudentData.dart page
// widget.userId = userCredential.user!.uid;
setState(() {
widget.userId = userCredential.user!.uid;
print("User id is : " + userCredential.user!.uid);
});
print("Widget User id is : " + widget.userId);
//show succuful log-in meesage
openSnackbar(
context, "Log-in Successfull", Color.fromARGB(255, 70, 213, 92));
//after login go to profile Page
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context) => FirstPage()));
} on FirebaseAuthException catch (e) {
//for no user Found
if (e.code == 'user-not-found') {
//for stoping the loading indicator when user get this error
Future.delayed(
Duration(seconds: 0),
() {
setState(() {
isLodaing = false;
});
},
);
//show Snack Bar when this error occur
openSnackbar(context, "No User Found for this e-mail", Colors.red);
}
//for Wrong Password
else if (e.code == 'wrong-password') {
//for stoping the loading indicator when user get this error
Future.delayed(
Duration(seconds: 0),
() {
setState(() {
isLodaing = false;
});
},
);
//show Snack Bar when this error occur
openSnackbar(context, "Wrong Password", Colors.red);
}
}
}
}
@override
void dispose() {
emailController.dispose();
passwordController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
backgroundColor: HexColor("#F9B684"),
body: GestureDetector(
//when user tap on screen tahat time keybord disumissed
//this is use for avoiding overflow screen
onTap: () => FocusScope.of(context).unfocus(),
child: SingleChildScrollView(
child: Column(
// this is main Column
children: [
//Heading
Container(
margin: EdgeInsets.only(top: 80, left: 20),
padding: EdgeInsets.only(left: 75, top: 13),
height: 80,
width: 265,
// color: Colors.white,
child: Text(
'Login',
style: TextStyle(
fontFamily: 'Ubuntu',
fontWeight: FontWeight.bold,
fontSize: 43,
color: HexColor("#2D0C03"),
),
),
),
//for image
Container(
margin: EdgeInsets.only(left: 10),
height: 200,
width: 265,
// color: Colors.white,
child: Image.asset("assets/images/login.gif",
fit: BoxFit.cover),
),
const SizedBox(height: 17),
//for TextFileds
Form(
key: _key,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 23.0),
child: Column(
children: [
//for E-mail Text Filed
TextFormField(
keyboardType: TextInputType.emailAddress,
//for move to cursor next Text automatically
textInputAction: TextInputAction.next,
//for autofil e-mail
autofillHints: [AutofillHints.email],
controller: emailController,
decoration: InputDecoration(
filled: true,
fillColor: Colors.white,
prefixIcon: Icon(
Icons.email,
color: HexColor("#002C00"),
),
hintText: "e-mail",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(33)),
focusedBorder: OutlineInputBorder(
borderSide:
BorderSide(color: HexColor("#002C00")),
borderRadius: BorderRadius.circular(25.7),
),
enabledBorder: UnderlineInputBorder(
borderSide:
const BorderSide(color: Colors.white),
borderRadius: BorderRadius.circular(25.7),
),
),
//for validation
validator: (value) =>
value != null && !EmailValidator.validate(value)
? 'Enter valid e-mail'
: null,
),
const SizedBox(height: 10),
//for Password Text Filed
TextFormField(
controller: passwordController,
decoration: InputDecoration(
filled: true,
fillColor: Colors.white,
prefixIcon: Icon(
Icons.password,
color: HexColor("#002C00"),
),
hintText: "password",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(33)),
focusedBorder: OutlineInputBorder(
borderSide:
BorderSide(color: HexColor("#002C00")),
borderRadius: BorderRadius.circular(25.7),
),
enabledBorder: UnderlineInputBorder(
borderSide:
const BorderSide(color: Colors.white),
borderRadius: BorderRadius.circular(25.7),
),
),
//for validation
validator: (value) {
if (value == null || value.isEmpty) {
return "Please enter password";
}
return null;
},
),
//for forget Password
Container(
margin: const EdgeInsets.only(top: 4),
// color: Colors.yellow,
height: 35,
width: MediaQuery.of(context).size.width,
alignment: Alignment.bottomRight,
child: TextButton(
onPressed: () {
//goto Forget Password Screen
nextScreen(context, ForgetPassword_Page());
},
child: const Text(
"Forgot Password",
textAlign: TextAlign.right,
style: TextStyle(
fontFamily: 'Gotham',
color: Color(0xff1778F2),
fontSize: 14.5),
),
),
),
const SizedBox(height: 9),
//for sign-in Button
SizedBox(
height: 50,
width: 170,
child: ElevatedButton.icon(
style: ElevatedButton.styleFrom(
primary: HexColor("#98504B"),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50),
),
),
//for loading indicator and Text
icon: isLodaing
? const SizedBox()
: const Icon(Icons.arrow_forward, size: 24),
label: isLodaing
? Row(
children: [
//for circular indicator
Container(
margin:
const EdgeInsets.only(left: 7),
height: 25,
width: 25,
child: CircularProgressIndicator(
color: HexColor("#2D0C03"),
strokeWidth: 3.5,
backgroundColor: Colors.white,
),
),
//for text
Container(
margin:
const EdgeInsets.only(left: 7),
child: Text(
"Please Wait..",
style: TextStyle(
fontFamily: 'Gotham',
color: Colors.white),
),
),
],
)
: const Text(
'Sign-in',
style: const TextStyle(
fontFamily: 'Gotham', fontSize: 22),
),
//here we call method name signup for storing data in firebase
onPressed: () async {
//for validation
if (_key.currentState!.validate()) {
isLodaing = true;
setState(() {
//when user enter email & password then store those email and passwors in variable which intialize in top
email = emailController.text;
password = passwordController.text;
});
//for Showing Loaing Indicator
Future.delayed(
Duration(seconds: 3),
() {
setState(() {
isLodaing = true;
});
},
);
//for user login
userLogin();
}
//after run above line of code this Stop the Loading Indicator
Future.delayed(
Duration(seconds: 3),
() {
setState(() {
isLodaing = false;
});
},
);
},
),
),
//for sign-up opotion below login button
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Does Not Have Account? '),
TextButton(
onPressed: () {
nextScreen(context, RegistrationPage());
},
child: const Text(
"Sign-UP",
style: TextStyle(
letterSpacing: 0.2,
fontFamily: "Ubuntu",
fontSize: 16,
color: Color(0xff1778F2),
),
),
)
],
),
),
],
),
),
),
]),
),
),
),
);
}
}
UserData controller Class:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:get/get.dart';
import 'package:gtu_all_in_one/Pages/LoginPage.dart';
//this class help for fetching current user info from firebase
class StudentDataController extends GetxController {
final firebaseInstance = FirebaseFirestore.instance;
//after data fetch insert data in this
Map StudentProfileData = {
'name': '',
'EnrollmentNo': '',
'Email': '',
'Branch&Sem': ''
};
//create loginpage instance for getting current user userid , using this we fetch the data
LoginPage authController = LoginPage();
@override
void onReady() {
super.onReady();
getStudentProfileData();
}
Future<void> getStudentProfileData() async {
// print("user id ${authController.userId}");
try {
var response = await firebaseInstance
.collection('users')
.where('user_Id', isEqualTo: authController.userId)
.get();
// response.docs.forEach((result) {
// print(result.data());
// });
if (response.docs.length > 0) {
StudentProfileData['name'] = response.docs[0]['name'];
StudentProfileData['EnrollmentNo'] = response.docs[0]['EnrollmentNo'];
StudentProfileData['Email'] = response.docs[0]['Email'];
StudentProfileData['Branch&Sem'] = response.docs[0]['Branch&Sem'];
}
print(StudentProfileData);
} on FirebaseException catch (e) {
print(e);
} catch (error) {
print(error);
}
}
}
And profile Page where i trying to display current user data:
class ProfilePage extends StatefulWidget {
const ProfilePage({Key? key}) : super(key: key);
@override
State<ProfilePage> createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
//when user come in profile page after login that time this create instance of StudentDataController and go to StudentData Page
final StudentDataController controller = Get.put(StudentDataController());
@override
Widget build(BuildContext context) {
// for logout button
final sp = context.watch<SignInProvider>();
return SafeArea(
child: Scaffold(
resizeToAvoidBottomInset: false,
body: Center(
child: Column(
children: [
SizedBox(height: 300),
Text("Name : ${controller.StudentProfileData['name']} "),
Text(
"Enrollment No : ${controller.StudentProfileData['EnrollmentNo']} "),
Text("Email : ${controller.StudentProfileData['Email']} "),
Text(
" Branch& Sem : ${controller.StudentProfileData['Branch&Sem']} "),
SizedBox(height: 10),
SizedBox(height: 10),
//for Opening QR Code Scanner
SizedBox(
height: 50,
width: 250,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
primary: HexColor("#48EDC5"),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(22),
),
),
child: Row(
children: [
//for text
Container(
margin: const EdgeInsets.only(left: 13),
child: Text(
"Mark Attendance",
style: TextStyle(
fontFamily: 'Gotham',
color: HexColor("#002C00"),
fontSize: 20),
),
),
//for Icone
Container(
margin: EdgeInsets.only(left: 5),
child: Icon(
Icons.qr_code_scanner,
size: 22,
color: HexColor("#002C00"),
),
),
],
),
//goto QR Code Scanner Page
onPressed: () {
nextScreen(context, QRCodeScanner());
},
),
),
SizedBox(height: 10),
//for LogOut Button
SizedBox(
height: 50,
width: 150,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
primary: HexColor("#48EDC5"),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(22),
),
),
child: Row(
children: [
//for text
Container(
margin: const EdgeInsets.only(left: 13),
child: Text(
"log Out",
style: TextStyle(
fontFamily: 'Gotham',
color: HexColor("#002C00"),
fontSize: 20),
),
),
//for Icone
Container(
margin: EdgeInsets.only(left: 5),
child: Icon(
Icons.arrow_forward_ios,
size: 22,
color: HexColor("#002C00"),
),
),
],
),
//goto SignUp Page
onPressed: () {
sp.userSignOut();
nextScreenReplace(context, FirstPage());
},
),
),
],
),
),
),
);
}
}