the problem that am trying to get value from "getThatWishlist" but it returns instead "Instance of 'Future<Map<dynamic, dynamic>>'"
Future<Map<dynamic, dynamic>> getThatWishlist(String? wishlistname) async {
FirebaseFirestore db = FirebaseFirestore.instance;
return await db
.collection('wishlists')
.doc(currentUserId)
.get()
.then((snapshot) async {
if (snapshot.data() == null) {
return {};
} else {
Map<dynamic, dynamic> wishlistData = {};
wishlistData =
await snapshot.data()!['userWishlists'][wishlistname]['UserItems'];
return wishlistData;
}
});
}
void createWishlistForSharedUser(String? ShareUid) async {
FirebaseFirestore db = FirebaseFirestore.instance;
await db.collection('wishlists').doc(ShareUid).set({
'sharedWishlistsWithUser': {
wishlistName: {
'UserItems': {getThatWishlist(wishlistName) //the problem is here
}
},
'wishlist owner email': currentUserEmail,
},
}, SetOptions(merge: true));
}
How to fix that problem ?
You should do something like this instead:
void createWishlistForSharedUser(String? ShareUid) async {
/// add this line
var userItems = await getThatWishlist(wishlistName);
FirebaseFirestore db = FirebaseFirestore.instance;
await db.collection('wishlists').doc(ShareUid).set({
'sharedWishlistsWithUser': {
wishlistName: {
/// update line below
'UserItems': {userItems}
},
'wishlist owner email': currentUserEmail,
},
}, SetOptions(merge: true));
}
Related
I'm trying to return a list of values.
Assessing by using Late
late List userLikes = userListLikes.getUsersLikes();
My Code:
class GetUserLikes {
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
final user = FirebaseAuth.instance.currentUser!;
List getUsersLikes() {
try {
print('start');
final docRef = _firestore.collection("user_details").doc(user.uid);
docRef.get().then((DocumentSnapshot doc) async {
final data = doc.data() as Map<String, dynamic>;
print("data[user_likes]");
print(data['user_likes']);
print('end');
return await data['user_likes']; // → not awaiting
},
onError: (e) => print("Error getting document: $e"),
);
} catch (err) {
print('There was an error');
}
return ['Nothing Returned'];
}
}
The function is not completing and returns before the await has finished which is not the array I need.
start
[Nothing Returned] (Returns without completing)
data[user_likes]
[967, 769, 887, 820, 860, 833, 857, 1017] → The Array I want returned
end
As someone downvoted this answer here is the full working code:
This get an Array field from a Firestone database and then returns a list dynamic.
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
class GetUserLikes {
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
final user = FirebaseAuth.instance.currentUser!;
Future<List> getUsersLikes() async {
// Get the list of user likes from the Firestone Database and then
// return the list so it will only show the users likes on the profile page.
try {
final docRef = _firestore.collection("user_details").doc(user.uid);
DocumentSnapshot doc = await docRef.get(); // Await
final data = doc.data() as Map<String, dynamic>;
return data['user_likes'];
} catch (err) {
print('There was an error');
}
return ['Nothing Returned'];
}
Future<List> getLikes() async {
// Takes the Future<List> and turns it into a List<dynamic>
Future<List> userLikes = getUsersLikes();
List list = await userLikes;
return list; // Returns List<dynamic>
}
}
Then on the receiving Future builder it will have to be awaited.
GetUserLikes userLikesList = GetUserLikes();
List userLikes = await userLikesList.getLikes();
I have this code
checkUserValue(String user) async {
FirebaseFirestore _firestore = FirebaseFirestore.instance;
await _firestore.runTransaction((transaction) async {
DocumentReference userRef = _firestore
.collection("users")
.where("id", isEqualTo: "hhjhgjhfhgfhgfh");
DocumentSnapshot snapshot = await transaction.get(userRef);
String docc = snapshot.get("username");
print(docc);
if (docc == null) {
_userExist = false;
} else {
_userExist = true;
}
});
}
But am faced with this issue,
Please I need solution
where(...) function return Query<Map<String, dynamic>> not the DocumentReference
You need to pass the document path (DocumentReference) in the get() method. So, specify the correct document path
DocumentReference userRef = _firestore.collection('users').doc('hhjhgjhfhgfhgfh');
checkUserValue(String user) async {
FirebaseFirestore _firestore = FirebaseFirestore.instance;
await _firestore.runTransaction((transaction) async {
DocumentReference userRef =
_firestore.collection('users').doc('hhjhgjhfhgfhgfh');
DocumentSnapshot snapshot = await transaction.get(userRef);
String docc = snapshot.get('username');
print(docc);
if (docc == null) {
_userExist = false;
} else {
_userExist = true;
}
});
}
I have 2 data provider classes that extend ChangeNotifier. Within each, there's a function to fetch data and at the end of them, I use notifyListeners() to notify the screens/listeners that the data changed. However, it seems that the listeners start getting notified endlessly instead of once and that creates a loop of reloading, circle indicators that don't go away, and a frozen screen. I don't get it.
Data providers:
class UsersDataProvider extends ChangeNotifier {
UsersDataProvider() : super();
static Map<int, QueryDocumentSnapshot<Object?>> usersMap = {};
Future<void> fetchUsers() async {
final userRef = FirebaseFirestore.instance.collection('users');
final QuerySnapshot result = await userRef.get();
final docs = result.docs.asMap();
usersMap = docs;
print(usersMap.length);
notifyListeners();
}
}
class PostsDataProvider extends ChangeNotifier {
PostsDataProvider() : super();
static Map<int, QueryDocumentSnapshot<Object?>> postsMap = {};
Future<void> fetchPosts() async {
UsersDataProvider.usersMap.forEach((index, resultValue) async {
final postsRef = FirebaseFirestore.instance
.collection('users')
.doc(resultValue.id)
.collection('posts');
final QuerySnapshot postsResult = await postsRef.get();
final postDocs = postsResult.docs.asMap();
postsMap = postDocs;
print('Post map: ${postsMap.length}');
notifyListeners();
});
}
}
Add listeners and reload data:
Future<void> fetchUsersAndPosts(bool initial) async {
if (!initial) {
setState(() {
postsLoading = true;
});
usersDataProvider.fetchUsers();
postsDataProvider.fetchPosts();
}
if (initial) {
usersDataProvider.addListener(() {
print('changed');
setState(() {
fetchUsersAndPosts(false);
});
});
}
if (initial) {
postsDataProvider.addListener(() {
setState(() {
fetchUsersAndPosts(false);
});
});
}
UsersDataProvider.usersMap.forEach((index, value) async {
List<Post> posts = [];
PostsDataProvider.postsMap.forEach((index, value) {
final post = Post.fromJson(value.data() as Map<String, dynamic>);
posts.add(post);
setState(() {});
if (posts.length == PostsDataProvider.postsMap.length) {
setState(() {
postsList = posts;
postsList.sort((a, b) {
return b.date.compareTo(a.date);
});
postsLoading = false;
});
}
});
final profileInfo =
ProfileInfoObject.fromJson(value.data() as Map<String, dynamic>);
Profile profile = Profile(profileInfo, postsList.where((p) => p.uid == value.id).toList());
UserSearchResult user = (UserSearchResult(profile, value.id));
if (usersList.where((u) => u.uid == user.uid).toList().isEmpty) {
setState(() {
usersList.add(user);
});
}
});
setState(() {
postsList.sort((a, b) {
return b.date.compareTo(a.date);
});
});
}
Hello I’m new to flutter
I’m trying to retrieve the user data from his email but i got this error [Null is not a subtype of type String]
The data I’m trying to retrieve is not null
This is my code
class _ProfilePageState extends State<ProfilePage> {
late User user;
final _auth = FirebaseAuth.instance;
late User signedInUser;
var id;
var email;
var name;
var age;
var sex;
#override
void initState() {
super.initState();
onRefresh(FirebaseAuth.instance.currentUser);
getCurrentUser();
}
onRefresh(userCare)
{
setState(()
{
user = userCare;
});
}
void getCurrentUser()
{
try {
final user = _auth.currentUser;
if (user != null) {
signedInUser = user;
email = signedInUser.email;
id = signedInUser.uid;
}
} catch (e) {
print(e);
}
}
void getData() {
FirebaseFirestore.instance
.collection('users')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((doc) {
if (doc["email"] == signedInUser.email) {
name = doc['name'];
age = doc['age'];
sex = doc['sex'];
print(doc['name']);
}
});
});
}
This is my data
I want to retrieve then but i can’t because it says null how to fix the error?
this is the data I’m trying to retrieve
the error image
Please try this Code:
void getData() async {
await FirebaseFirestore.instance
.collection('users')
.get()
.then((value) {
for(var doc in value.docs) {
if (doc["email"] == signedInUser.email) {
name = doc.data()['name'];
age = doc.data()['age'];
sex = doc.data()['sex'];
print(doc.data()['name']);
}
}
});
}
I made a function for users to get daily points (every 24 Hours). The function is linked with Firebase Firestore.
My problem is that if I close the app, relaunch it and click the triggering button ($checkPoints). It will add extra points to database even if the user did it less than 24 Hours ago !
Can you please check the code under and help me fix this?
import 'dart:convert';
import 'dart:math';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:http/http.dart' as http;
class Authfirestore {
final String uid;
int points;
var dateFromApitme;
String lastTimeGotPointsFromFirebase;
Authfirestore({this.uid, this.points});
Firestore _firestore = Firestore();
Future checkPoints() async {
await dateApi();
if (dateFromApitme != null ) {
try {
if (lastTimeGotPointsFromFirebase != dateFromApitme && dateFromApitme != null) {
await getData();
dynamic result = _firestore
.collection('users')
.document('Jm7bx8NOE9Nfx6P8S1wD')
.setData({
'points': points + 1,
'LastTimeGotPoints' :dateFromApitme,
});
await getData();
print(result.toString());
trackingData();
} else {
print('You toke your cridit ');
}
} catch (e) {
print('Error in cehckpoints $e');
}
}
}
Future trackingData() async {
await Firestore.instance
.collection('users')
.document('Jm7bx8NOE9Nfx6P8S1wD')
.collection('tracking')
.document(_randomString(20))
.setData({
'date': DateTime.now(),
});
}
Future getData() async {
await Firestore.instance
.collection('users')
.document('Jm7bx8NOE9Nfx6P8S1wD')
.get()
.then((DocumentSnapshot ds) {
points = ds.data['points'];
lastTimeGotPointsFromFirebase = ds.data['LastTimeGotPoints'];
print('number of points is $points');
});
}
String _randomString(int length) {
va
r rand = new Random();
var codeUnits = new List.generate(length, (index) {
return rand.nextInt(33) + 89;
});
return new String.fromCharCodes(codeUnits);
}
Future dateApi() async {
var response =
await http.get('http://worldtimeapi.org/api/timezone/Asia/Muscat');
if (response != null) {
var data0 = jsonDecode(response.body);
var data01 = data0['datetime'];
dateFromApitme = data01.substring(0, 9);
} else {
dateFromApitme = null;
print('Please Check Your internet');
}
}
}