Reputation: 35
I want to get data of authenticated user from firestore and put them in variables in flutter, I do not need to display them on the screen I just want to store them in variables : I created file data.dart It has only variables . this is the file contains the variables(data.dart) (I dont have statefull widget or stateless widget) :
and this is the file where I called The variables(firbaseapi.dart):
String myId = "AfhUxYFIaHTvSOyOPlh14essssq9pJpW2"; // I want to get user id here
String myUsername = 'Sabri'; // I want to get username here
String myUrlAvatar = 'http//kdkskdskd'; // I want to get avatar URL here
I tried this but I got an error : A value of type 'Future' can't be assigned to a variable of type 'DocumentSnapshot'. Try changing the type of the variable, or casting the right-hand type to 'DocumentSnapshot'
User user = FirebaseAuth.instance.currentUser;
DocumentSnapshot snap =
FirebaseFirestore.instance.collection('Users').doc(user.uid).get();//error appear here
String myId = snap['uid'];
String myUsername = snap['name'];
String myUrlAvatar = snap['avatarurl'];
Upvotes: 0
Views: 5332
Reputation: 495
working example!
imports
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
Global
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
String myId = '';
String myUsername = '';
String myUrlAvatar = '';
Method to get data from firestore.
void _getdata() async {
User user = _firebaseAuth.currentUser;
FirebaseFirestore.instance
.collection('users')
.doc(user.uid)
.snapshots()
.listen((userData) {
setState(() {
myId = userData.data()['uid'];
myUsername = userData.data()['name'];
myUrlAvatar = userData.data()['avatarurl'];
});
}
Get data when screen starts in a stateful widget you can also call method on button press.
@override
void initState() {
super.initState();
_getdata();
}
Upvotes: 1
Reputation: 419
DocumentSnapshot snap = FirebaseFirestore.instance.collection('your collection').get();
String myId = snap['myId'];
String myUsername = snap['myUsername'];
String myUrlAvatar = snap['myUrlAvatar'];
Update:
User user = FirebaseAuth.instance.currentUser;
DocumentSnapshot snap = FirebaseFirestore.instance.collection('Users').doc(user.uid).get();
String myId = snap['uid'];
String myUsername = snap['name'];
String myUrlAvatar = snap['avatarurl'];
Upvotes: 0