Filtering on Flutter Dart Firestore - flutter

How do i apply the filter Bloc output of:
var genders = state.filter.genderFilters
.where((filter) => filter.value)
.map((filter) => filter.gender.gender)
.toList();
To this search repository:
Future<User> getFilteredUser(userId) async {
User _user = User();
List<String> chosenList = await getChosenList(userId);
User currentUser = await getUserInterests(userId);
await _firestore.collection('users').getDocuments().then((users) {
for (var user in users.documents) {
if ((!chosenList.contains(user.documentID)) &&
(user.documentID != userId) &&
(user['gender'] == ) //???????
)
{
_user.uid = user.documentID;
_user.name = user['name'];
_user.photo = user['photoUrl'];
_user.age = user['age'];
_user.location = user['location'];
_user.gender = user['gender'];
break;
}
}
});
return _user;
}
I am trying to do somthing like this but on the firestore query:
List<User> filteredusers = User.filteredUsers
.where(
(user) => genders.any(
(gender) =>
user.genderCategory.contains(gender),
),
)
.toList();
Thanks in advance

Related

The value obtained from the database is not applied to the variable

I have a function to get a value from a sqlite database. How do I set this value to a variable?
Get value from DB
getPref(Setting setting) async {
var dbClient = await db;
try {
dbClient.query('settings',
where: 'name = ?',
whereArgs: [setting.name],
columns: ['value']).then((data) {
List<Map<String, dynamic>> s = data;
List<String> list = [];
for (var x in s) {
x.forEach((k, v) => list.add(v));
}
print("NAME: ${setting.name} VALUE: ${list[0]}");
return list[0];
});
} on Exception catch (ex) {
print(ex.toString());
}
}
Result:
NAME: mainPage VALUE: all
But when I put this value it doesn't apply, it throws null.
String page = "";
getPage() {
DBHelper database = DBHelper();
database.getPref(Setting(name: 'mainPage')).then((val) {
setState(() {
print("VAL " + val.toString());
page = val;
});
});
}
Unhandled Exception: type 'Null' is not a subtype of type 'String'
Try replacing:
getPref(Setting setting) async {
var dbClient = await db;
try {
dbClient.query('settings',
where: 'name = ?',
whereArgs: [setting.name],
columns: ['value']).then((data) {
List<Map<String, dynamic>> s = data;
List<String> list = [];
for (var x in s) {
x.forEach((k, v) => list.add(v));
}
print("NAME: ${setting.name} VALUE: ${list[0]}");
return list[0];
});
}
with:
getPref(Setting setting) async {
var dbClient = await db;
try {
var data = await dbClient.query('settings',
where: 'name = ?',
whereArgs: [setting.name],
columns: ['value']);
List<Map<String, dynamic>> s = data;
List<String> list = [];
for (var x in s) {
x.forEach((k, v) => list.add(v));
}
print("NAME: ${setting.name} VALUE: ${list[0]}");
return list[0];
}
What's wrong?
When querying your db you are not waiting to complete the query before returning the list[0]. In other words, you are returning your list[] before getting the data from the database as .then doesn't block the execution onwards and prematurely executes return list[0] which you don't want.

Flutter & Firebase - Get a specific field from document

I have been trying to get a specific field from a specific document. I need token for toWho. But I always got null. How do I fix this?
Main Code is
Future<String> getUserToken(String toWho) async {
DocumentSnapshot _doc = await FirebaseFirestore.instance.doc("tokens/" + toWho).get();
if (_doc != null) {
Map<String, dynamic> _data = _doc.data();
return _data["token"];
} else {
return null;
}
}
in Repository
Future<bool> sendMessage(
MessageModel sendingMessage, UserModel currentUser) async {
if (appMode == AppMode.DEBUG) {
return true;
} else {
var _writePrcs = await _firestoreDBService.saveMessage(sendingMessage);
if (_writePrcs) {
var _token = "";
if (_userToken.containsKey(sendingMessage.toWho)) {
_token = _userToken[sendingMessage.toWho];
print("Token lokalden geldi.");
} else {
_token = await _firestoreDBService.getUserToken(sendingMessage.toWho);
_userToken[sendingMessage.toWho] = _token;
print("Token veritabanından geldi.");
}
Thanks for your help from now on
Try ...........
Future<String> getUserToken(String toWho) async {
DocumentSnapshot _doc = await
FirebaseFirestore.instance.collection("tokens/groupChatId/message").doc(toWho).get();
if (_doc != null) {
Map<String, dynamic> _data = _doc.data();
return _data["token"];
} else {
return null;
}
}

How to transform a Future method in a Stream method to feed a list

I have this method to feed my list, but with it i'm not able to change items dynamically ( add items, drop it...) :
loadLab(String submenu, [int limit]) async {
var parts = submenu.split('/');
var pathSlashless = parts[0].trim();
var subPathSlashless = parts.sublist(1).join('/').trim();
var snapshot = await _storage.ref().child("/${submenu}");
var retorno = await snapshot.listAll();
List<ItemLab> conteudo = [];
if(subPathSlashless.isEmpty || subPathSlashless == null){
retorno.prefixes.forEach((element) {
conteudo.add(
ItemLab(
tipo: 'PASTA',
elemento: element,
),
);
});
}
if(limit != null){
if(conteudo.length > limit){
hasMore = true;
return Stream.value(conteudo);
}else{
hasMore = false;
print("menor quen ove");
}
}
}
try {
if(subPathSlashless.isNotEmpty){
print(subPathSlashless);
List items;
await databaseReference
.collection("lab_${pathSlashless}_url")
.snapshots().forEach((element) {
element.docs.forEach((f) {
if(f.data()['videos'] != null){
items == null ? items = f.data()['videos'] :
items.addAll(f.data()['videos']);
};
print("ITEMS :::: >>> ${items}");
});
});
}catch(e){
print(e);
}
pathSlashless = null;
subPathSlashless = null;
conteudo = checkDuplicateFolder(conteudo, submenu);
print(conteudo);
return Stream.value(conteudo);
}
and the list>
return StreamBuilder(
stream: ctrlLab.loadLab(submenu),
throw this error:
type 'Future' is not a subtype of type 'Stream'
What I need to do to Make the return a Stream instead of a Future

issue with geting all data from sqflite database

i have been trying to get all my data from a sqflite database, when i try to get a single data, this works totally fine:
Future<dynamic> getUser() async {
final db = await database;
var res = await db.query("files");
if (res.length == 0) {
return null;
} else {
var resMap = res[0];
return resMap;
}
}
but when i try to get all data using a for loop like the example below, i get an error
Future<dynamic> getUser() async {
final db = await database;
var res = await db.query("files");
var resMap;
var count = res.length;
if (count != 0) {
for (int i = 0; i < count; i++) {
resMap.add(res[i]);
}
}
return resMap;
}
the error says:
The method 'forEach' was called on null.
Receiver: null
Tried calling: forEach(Closure: (dynamic, dynamic) => Null)
i understand that it says that I've got no data,
and i also tried to remove the if statement, but still no luck!
change this method:
EDIT
Future<List<Map>> getUser() async {
final db = await database;
var res = await db.query("files");
List<Map> resMap = [];
if (res != null res.length > 0) {
for (int i = 0; i < count; i++) {
resMap.add(res[i]);
}
return resMap;
} else
{
return null;
}
}
try this in you widget
List<Map> newUser = [];
#override
void initState() {
super.initState();
getUser();
}
getUser() async {
final _userData = await DBProvider.db.getUser();
if(_userData != null ){
setState(() {
newUser = _userData;
});
} else{
setState(() {
newUser =[];
});
}
}

How to Update fields using where conditions Current user = Key ( User ID) firestore and flutter

Hello I'm using flutter and firebase so I have firestore I have on collocation name Institutes and in document has names of Institutes and my Fields I have profile data ….no I need update some fields by where conditions where currant user = Key User id in the fields*
Screenshot
onPressed: ()async {
final FirebaseAuth auth = FirebaseAuth.instance;
final user = await auth.currentUser();
final iduser = user.uid;
final emailuser = user.email;
final snapshot = await Firestore.instance.collection("Institute")
.document(_Institute_name.text).get();
if (snapshot.exists) {
print(this name is existd);
} else {
await DataBaseService(email: emailuser,
uid: iduser,
Document: _Institute_name.text)
.CreateCollectionInofwithImage(
_Institute_name.text, Institute_address.text,
int.parse(Institute_phone.text), _image).then((isdone) {
setState(() {
Institute_address.clear();
Institute_phone.clear();
_Institute_name.clear();
_image = null;
});
});
}
}
Okay try this
onPressed: ()async {
final FirebaseAuth auth = FirebaseAuth.instance;
final user = await auth.currentUser();
final iduser = user.uid;
final emailuser = user.email;
QuerySnapshot snapshot = await Firestore.instance
.collection('Institute')
.where('user id', isEqualTo: iduser)//I think this is your field name from the
//picture it looks like theres a space in it
.getDocuments();
if (snapshot != null) {
Map<String,dynamic> document = snapshot.documents[0].data;
//Then you would reference this by document['fieldName']
} else {
await DataBaseService(email: emailuser,
uid: iduser,
Document: _Institute_name.text)
.CreateCollectionInofwithImage(
_Institute_name.text, Institute_address.text,
int.parse(Institute_phone.text), _image).then((isdone) {
setState(() {
Institute_address.clear();
Institute_phone.clear();
_Institute_name.clear();
_image = null;
});
});
}
}