Hi I'am new to Flutter making an app for booking appointments which require to screens for two types of users i.e. patient and doctor.
class DashboardPage extends StatefulWidget {
#override
_DashboardPageState createState() => _DashboardPageState();
}
class _DashboardPageState extends State<DashboardPage> {
UserProvider userProvider;
final AuthMethods _authMethods = AuthMethods();
#override
void initState() {
super.initState();
SchedulerBinding.instance.addPostFrameCallback((_) async {
userProvider = Provider.of<UserProvider>(context, listen: false);
await userProvider.refreshUser();
_authMethods. getUserDetails();
});
}
User user = User();
#override
Widget build(BuildContext context) {
if (user.role == 'patient') {
return PatientHomePage();
}
else if (user.role == 'doctor') {
return DoctorHomePage();}
return Container(color: Colors.red,);
}
}
role variable is defined in another dart file:
class User { String uid; String name; String email; String role = "patient"; String profilePhoto; User({ this.uid, this.name, this.email, this.role, this.profilePhoto, }); ........... }
the default value "patient" is assigned to it when a user logs in. Future<void> addDataToDb(FirebaseUser currentUser) async { User user = User( uid: currentUser.uid, email: currentUser.email, name: currentUser.displayName, profilePhoto: currentUser.photoUrl, role: "patient"); firestore .collection(USERS_COLLECTION) .document(currentUser.uid) .setData(user.toMap(user)); } all this is happening in another dart file
But this logic is not working as expected as it's showing only the red screen on phone which implies that
there is some issue in getting user.role from firebase.
Please help me...
class DashboardPage extends StatefulWidget {
#override
_DashboardPageState createState() => _DashboardPageState();
}
class _DashboardPageState extends State<DashboardPage> {
UserProvider userProvider;
final AuthMethods _authMethods = AuthMethods();
User user = User();
#override
void initState() {
super.initState();
SchedulerBinding.instance.addPostFrameCallback((_) async {
userProvider = Provider.of<UserProvider>(context, listen: false);
/// This method is future method so it might happen that after widget render you are getting response.
await userProvider.refreshUser();
/// seState will rebuild your widget with new user details
setState(() {
user = _authMethods. getUserDetails();
});
});
}
#override
Widget build(BuildContext context) {
if (user.role == 'patient') {
return PatientHomePage();
}
else if (user.role == 'doctor') {
return DoctorHomePage();}
return Container(color: Colors.red,);
}
}
Related
I am stuck for hours now on this problem.
I have no problem to access the final currentUser = loggedInUser.email;when the getCurrentUser function is defined and called in the same class (SlateScreen).
My SlateScreen Class ad MessageStream Class are both in the same .dart file. So this here works:
final firestore = Firestore.instance;
/// loggedInUser variable for fetching the user email later
FirebaseUser loggedInUser;
DatabaseMethods databaseMethods = DatabaseMethods();
class TheSlateScreen extends StatefulWidget {
static String id = 'theslate_screen';
#override
_TheSlateScreenState createState() => _TheSlateScreenState();
}
class _TheSlateScreenState extends State<TheSlateScreen> {
final _auth = FirebaseAuth.instance;
// call getCurrentUser in initState
#override
void initState() {
super.initState();
getCurrenUser();
}
getCurrentUser() async {
try {
final user = await _auth.currentUser();
if (user != null) {
loggedInUser = user;
print(loggedInUser);
}
} catch (e) {
print(e);
}
}
class MessagesStream extends StatelessWidget {
#override
Widget build(BuildContext context) {
// fetch the email from my getCurrentUser function
final currentUser = loggedInUser.email;
But I get "The getter email was called on null" error if I define my getCurrentUser() function in the DatabaseMethods Class, and then call it in the SlateScreen class' via
#override
void initState() {
super.initState();
databaseMethods.getCurrentUser(_auth);
}
My DatabaseMethods Class:
class DatabaseMethods {
FirebaseUser loggedInUser;
getCurrentUser(FirebaseAuth _auth) async {
try {
final user = await _auth.currentUser();
if (user != null) {
loggedInUser = user;
}
} catch (e) {
print(e);
}
}
I tried all kind of adjustments, but didn t get anywhere...
UPDATE / SOLUTION:
Thanks to the the anwsers provided, I found a way:
in my DatabaseMethods class I simply return the user:
Class DatabaseMethods {
getCurrentUser(FirebaseAuth _auth) async {
try {
final user = await _auth.currentUser();
if (user != null) {
return user;
}
} catch (e) {
print(e);
}
}
}
and in the SlateScreen Class, I am using a helper function that I can call in initState():
#override
void initState() {
super.initState();
logInUser(_auth);
}
logInUser(_auth) async {
loggedInUser = await DatabaseMethods().getCurrentUser(_auth);
}
In this snippet:
// fetch the email from my getCurrentUser function
final currentUser = loggedInUser.email;
The loggedInUser variable is only set once the getCurrentUser method has completed. So you can't just do loggedInUser.email anywhere in your code, but can only do that after you've made sure getCurrentUser has completed.
So this would work fine:
await databaseMethods.getCurrentUser(_auth);
final currentUser = loggedInUser.email;
Given what you shared, it may be able to add that await in your initState:
#override
void initState() {
super.initState();
await databaseMethods.getCurrentUser(_auth);
}
You need to initialize loggedInUser, just do the following:
loggedInUser = await FirebaseAuth.instance.currentUser();
final currentUser = loggedInUser.email;
I'm having a simple problem which is how to get specific values from database Firebase.
For example, I want to get the value of "name" and put it in text. How can I do that? Can you write a detailed code?
class _HomePageState extends State<HomePage> {
String myuid;
FirebaseUser currentUser;
// To get id
void _loadCurrentUser() {
FirebaseAuth.instance.currentUser().then((FirebaseUser user) {
setState(() { // call setState to rebuild the view
this.currentUser = user;
});
});
}
#override
void initState() {
super.initState();
_loadCurrentUser();
}
#override
Widget build(BuildContext context) {
myuid = currentUser.uid;
var getname;
Future<void> getName() async {
DocumentSnapshot ds =
await Firestore.instance.collection('users').document(myuid).get();
getname = ds.data['name'];
}
Try
String name;
Future<null> getName() async {
DocumentSnapshot document = await Firestore.instance.collection('users').document(FirebaseUser().uid).get();
name = document.data['name']
}
This is how you can get data from the Firestore Database Document once
val docRef = db.collection("users").document("mhPtwy..........")
docRef.get()
.addOnSuccessListener { document ->
if (document != null) {
Log.d(TAG, "DocumentSnapshot data: ${document.data}")
} else {
Log.d(TAG, "No such document")
}
}
.addOnFailureListener { exception ->
Log.d(TAG, "get failed with ", exception)
}
This is a kind of cheeky way to get the data and store it in a variable
var name;
Future<void> getName(){
DocumentSnapshot ds = await
Firestore.instance.collection('users').document(uid).get();
name = ds.data['name']
}
then just throw that in your text field
Text(name);
I'm trying to log out from FirebaseAuth, but even though the user is null after I logged out, it seems like the instance is somehow still cached.
When I log out and in again, the user.metadata.lastSignInTime and the FirebaseAuth.instance.hashCode are still the same as before I logged out.
That causes, that my onboarding is displayed even after the second login as I'm checking if user.creationTime == user.lastSignInTime.
My _logOut Method:
void _logOut(BuildContext context) async {
await GoogleSignIn().signOut();
await FirebaseAuth.instance.signOut();
}
The initial SignUp Page whitch is beeing called when user == null :
class SignUpPage extends StatefulWidget {
final String title;
SignUpPage({Key key, this.title}) : super(key: key);
#override
SignUpPageState createState() => SignUpPageState();
}
class SignUpPageState extends State<SignUpPage> {
final FirebaseAuth _auth = FirebaseAuth.instance;
bool isloaded = false;
#override
void initState() {
super.initState();
//detects when user logs out:
_auth.onAuthStateChanged.listen((user) => {
if (user == null)
{
//This page is the first one in the route
Navigator.of(context).popUntil((route) => route.isFirst),
setState(() {
isloaded = true;
}),
}
});
// Enabled persistent log-ins by checking the Firebase Auth instance for previously logged in users
_auth.currentUser().then((user) {
setState(() {
isloaded = true;
});
if (user != null) {
_pushPage(context, HomePage());
}
});
}
#override
Widget build(BuildContext context) {
//Building Page here
}
}
I'm just starting with Flutter, but I tried everything I could think of to actually fully dispose the FirebaseAuth.instance in _logOut() without success.
My implementation repository
in main method i have this lines of code to connect to database and work fine
Future<void> main() async {
final database = await $FloorAppDatabase.databaseBuilder('flutter_database.db').build();
final userDao = database.userDao;
runApp(MaterialApp(...);
}
now i'm trying to use this codes
final database = await $FloorAppDatabase.databaseBuilder('flutter_database.db').build();
final userDao = database.userDao;
from class, for example:
Future<void> main() async {
MyDatabase myDatabase = MyDatabase();
final userDao = myDatabase.userDao;
runApp(MaterialApp(...);
}
unfortunately i get null for userDao in this implementation, i think in that witch i use async i should be change that and use then()
class MyDatabase {
UserDao userDao;
Future<UserDao> initialDatabase() async {
final database = await $FloorAppDatabase.databaseBuilder('flutter_database.db').build();
return database.userDao;
}
}
#dao
abstract class UserDao{
#Query('SELECT * FROM User LIMIT 1')
Stream<User> getUserInfo();
#insert
Future<void> insertUserInformation(User user);
}
UPDATED: implementation solution on scope model
class MydbModel extends Model {
MyDatabase myDatabase = MyDatabase();
Future _doneFuture;
MydbModel() {
_doneFuture= myDatabase.initialDatabase();
}
Future get initializationDone => _doneFuture;
}
class MyDatabase {
AppDatabase db;
UserDao userDao;
Future<void> initialDatabase() async {
db = await $FloorAppDatabase.databaseBuilder('flutter_database.db').build();
}
UserDao getUserDao() {
return db.userDao;
}
}
main() {
runApp(MaterialApp(
title: 'floor sample',
home: App(),
));
}
class App extends StatefulWidget {
App({Key key}) : super(key: key);
#override
State<App> createState() => _AppState();
}
class _AppState extends State<App> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: ScopedModel(
model: MydbModel(),
child: ScopedModelDescendant<MydbModel>(
builder: (context, _, model) => StreamBuilder<User>(
stream: model.myDatabase.userDao.getUserInfo(),
builder: (_, snapshot) {
if (!snapshot.hasData) {
return Text('user not found');
} else {
return Text('user found');
}
},
),
),
),
);
}
}
With given class implementation, you should call the function and wait until it completes:
MyDatabase myDatabase = MyDatabase();
final userDao = await myDatabase.initialDatabase();
Alternatively, if you don't want to recreate databse instance each time, consider assigning it to a class member
class MyDatabase {
AppDatabase db;
Future<void> initDb() async {
db = await $FloorAppDatabase.databaseBuilder('flutter_database.db').build();
}
UserDao getUserDao() {
return db.userDao;
}
// here may be other functions that use db
}
And the use it like this
MyDatabase myDatabase = MyDatabase();
await myDatabase.initDb();
final userDao = myDatabase.getUserDao();
// here you can call other functions from class
I want to declare a user object, that I will instantiate with an http request, and I want it to be global. How can I do it? With a Singleton? But how can I make this class also a Singleton? Or is there another way?
That is what I've done so far:
class User{
String username;
String password;
int id;
User({this.username, this.id});
factory User.fromJson(Map<String, dynamic> json){
return User(
username: json['name'],
id: json['id']
);
}
}
and then:
var user = await login(username, password, context);
In flutter, you should not make singletons. Instead, you should store it into a widget that exposes these data to all of its descendants.
Usually InheritedWidget
The reason being, with such architecture all the descendants are automatically aware of any change made to your "singleton".
A typical example would be the following:
#immutable
class User {
final String name;
User({this.name});
}
class Authentificator extends StatefulWidget {
static User currentUser(BuildContext context) {
final _AuthentificatorScope scope = context.inheritFromWidgetOfExactType(_AuthentificatorScope);
return scope.user;
}
final Widget child;
Authentificator({this.child, Key key}): super(key: key);
#override
_AuthentificatorState createState() => _AuthentificatorState();
}
class _AuthentificatorState extends State<Authentificator> {
#override
Widget build(BuildContext context) {
return _AuthentificatorScope(
child: widget.child,
);
}
}
class _AuthentificatorScope extends InheritedWidget {
final User user;
_AuthentificatorScope({this.user, Widget child, Key key}) : super(child: child, key: key);
#override
bool updateShouldNotify(_AuthentificatorScope oldWidget) {
return user != oldWidget.user;
}
}
which you have to instantiate like this:
new MaterialApp(
title: 'Flutter Demo',
builder: (context, child) {
return Authentificator(
child: child,
);
},
home: Home(),
);
and then use inside your pages like this:
#override
Widget build(BuildContext context) {
User user = Authentificator.currentUser(context);
...
}