Future<String> getCurrentUser() async {
final FirebaseUser user = await _auth.currentUser();
final uid = user.uid;
return uid;
}
I want to have user uid in the document but I cant get it .
Stream<List<RezervasyonListesi>> get rezervasonlarlistesi1 {
return rezervasyonCollectionRef
.document() // **In document I want refer to user uid ;**
.collection("rezerve")
.snapshots()
.map(_rezervasyonlistesifromsnap);
}
I tried this but didnt work
Stream<List<RezervasyonListesi>> get rezervasonlarlistesi {
getCurrentUser().then((value) {
return rezervasyonCollectionRef
.document(value)
.collection("rezerve")
.snapshots()
.map(_rezervasyonlistesifromsnap);
});
}
Stream<List< RezervasyonListesi>> is not a type of future because of that I cant use async in that function .Without ascyn how can I get my firebase user uid.
class of RezervasyonListesi
class RezervasyonListesi {
final String name;
final String address;
final String image;
final String rating;
final String description;
RezervasyonListesi(
{this.address, this.description, this.image, this.name, this.rating});
}
Try this.
Stream<List<RezervasyonListesi>> get rezervasonlarlistesi async*{
String currentUser = await getCurrentUser();
yield* rezervasyonCollectionRef.document(currentUser.uid).snapshots().map((snapshot){
return snapshot.data;
});
}
Related
I saw this example trying to get the User details from Firestore Firebase in Flutter. Unfortunately it gives me the error The instance member 'snap' can't be accessed in an initializer.
DocumentSnapshot snap = FirebaseFirestore.instance.collection('Users').doc().get() as DocumentSnapshot<Object?>;
String myId = snap['name'];
Yeah, you can't use snap there because you have not initialized the object.
Rather, move the usage into initState. Something like this:
class _MyHomePageState extends State<MyHomePage> {
DocumentSnapshot snap = await FirebaseFirestore.instance
.collection('Users')
.doc()
.get() as DocumentSnapshot<Object?>;
String myId;
#override
void initState() {
super.initState();
myId = snap['name'];
// should be myId = snap.get('name');
}
You can call it using async and await
String myId = '';
#override
void initState() {
super.initState();
initialize();
}
void initialize() async{
DocumentSnapshot snap = await FirebaseFirestore.instance.collection('Users').doc().get() as DocumentSnapshot<Object?>;
myId = snap['name'];
}
I am developing an app with Flutter and Firebase.
I want to store the _id with SharedPreferences permanently.
Therefore, i looked after it, but my code doesnt work at all. It always throws the error:
type 'Future' is not a subtype of type 'String'
Here is my code:
class Profile with ChangeNotifier {
String _id;
void setName(String name) {
const url =
'myurl';
http
.post(url, body: json.encode({'name': name, 'description': name}))
.then((response) {
_id = json.decode(response.body)['name'];
});
addID();
}
Future<void> updateName(String name, String id) async {
String url =
'myurl';
await http.patch(url,
body: json.encode({'name': 'Ein Titel', 'description': name}));
}
And here are my methods with the SharedPrefs:
String getID() {
return getIDOffline();
}
addID() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('id', _id);
}
getIDOffline() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
//Return String
String stringValue = prefs.getString('id');
return stringValue;
}
You have use wrong method for return string so you have to change String getID() to Future<String> getID(). And you can use like this.
getValue()async{
String value = await getID();
}
When you use async always try to add also Future.
like :
Future<returnType> methodName() async { }
In your code try to change
String getID(){ } to Future<String>getID() async{ }
I am trying to fill my CurrentUser object with the same information as the uid of the logged in user when my users login to the application
My databaseService :
final CollectionReference userCollection =
Firestore.instance.collection('users');
Future<User> getCurrentUserData(String uid) async{
var doc = userCollection.document(uid);
And My Home Page :
class HomeScreen extends StatefulWidget {
final FirebaseUser currentUser;
HomeScreen({#required this.currentUser});
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
And My CurrentUser Model :
class CurrentUser {
static String name;
static String lastName;
static String uid;
static String phone;
static String addresses;
static String photoString;
static int cityId;
static int districtId;
static List<Loss> userLosses;
}
But i cant figure out connect them
If you are using the firebase authentication then you can use FiresbaseAuth.instance.currentUser, it will return a FirebaseUser object that will contain the info of the current user.
I figure it like this:
Future<User> getCurrentUserData(String uid)async {
var docRef = await userCollection.document(uid).get();
User currentUser = User.fromJson(docRef.data);
currentUser.uid=docRef.documentID;
return currentUser;
}
docRef.data is <String,dynamic> map and just i change my user class like this:
factory User.fromJson(Map<String, dynamic> json) {
return User(
name: json['Name'].toString(),
lastName: json['LastName'].toString(),
phone: json['Phone'].toString(),
photoString: json['PhotoString'].toString(),
districtId: int.parse(json['DistrictId'].toString()),
cityId: int.parse(json['CityId'].toString()),
addresses: json['Addresess'].toString());
}
i'm trying to query a firestore collection with a dynamic path (user specific), it works hardcoded, but not dynamic with a variable, someone know the issue and can help?
Thanks in advance
final CollectionReference addressCollection =
Firestore.instance.collection('users/r9qClctByGXinYAmB2MqQNctgd53/addresses');
works.
This not:
final CollectionReference addressCollection =
Firestore.instance.collection('users/$userId/addresses');
userId is = r9qClctByGXinYAmB2MqQNctgd53
Full FirestoreDatabase code:
class FirestoreDatabase {
final _service = FirestoreService.instance;
static String userId;
void setUserId(uid) {
userId = uid;
}
final CollectionReference addressCollection =
Firestore.instance.collection('users/$userId/addresses');
// Adresses List Stream
Stream<List<Address>> get addressesStream {
return addressCollection.snapshots().map(_addressListFromSnapshot);
}
List<Address> _addressListFromSnapshot(QuerySnapshot snapshot) {
return snapshot.documents.map((doc) {
return Address.fromMap(doc.data);
}).toList();
}
}
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);