I want to acess the uname field of the current loggedin user . I added uname in the registration screen like this :
onPressed: () async {
try {
final newuser = await FirebaseAuth.instance
.createUserWithEmailAndPassword(
email: email ?? 'error',
password: password ?? 'error',
);
await FirebaseFirestore.instance
.collection('Users')
.add({' uname': username});
if (newuser != null) {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => home()),
);
}
} catch (e) {
print(e);
}
}
But I dont know how to acess it from another file or morespecifically I want to acess it on the profile screen . How can I acess the uname field from firestore in flutter?
CodePudding user response:
I think the better way to what you want is to set the document ID in the collection("Users") same as the uid of the user authenticated. So fetching details or in this case, uname will be easier.
For creating doc with docID same as user uid:
await FirebaseFirestore.instance
.collection('Users')
.doc(newUser.uid)
.add({' uname': username});
For fetching details:
final userData = await FirebaseFirestore.instance
.collection("Users")
.doc(FirebaseAuth.instance.currentUser!.uid)
.get();
CodePudding user response:
You should call the document in the initState
and set the value of string using setState
Code:
class ProfileScreen extends StatefulWidget {
const ProfileScreen({super.key});
@override
State<ProfileScreen> createState() => _ProfileScreenState();
}
class _ProfileScreenState extends State<ProfileScreen> {
String? name;
@override
void initState() {
FirebaseFirestore.instance
.collection('users')
.doc(FirebaseAuth.instance.currentUser?.uid)
.get()
.then((value) {
setState(() {
name = value.data()?['uname'];
});
});
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child:
name != null ? Text(name!) : const CircularProgressIndicator()),
);
}
}