Check if key exists in Firebase Firestore - android

I want to make a to-do list with task due date as an optional field, so I need to check if some tasks have dueDate and add it as a subtitle based on that. How can I check if a field exists inside a doc in a StreamBuilder?
class _TaskListState extends State<TaskList> {
var myStream;
#override
void initState() {
myStream = FirebaseFirestore.instance
.collection('tasks')
.doc(widget.uid)
.collection('mytasks')
.snapshots();
super.initState();
}
...
void _updateTaskDesc(
dynamic currTask, String newDesc, DateTime newDate, TimeOfDay newTime) {
FirebaseFirestore.instance
.collection('tasks')
.doc(widget.uid)
.collection('mytasks')
.doc(currTask['id'])
.update({
'desc': newDesc,
'dueDate': newDate.toString(),
'dueTime': newTime.toString(),
});
}
#override
Widget build(BuildContext context) {
return StreamBuilder(
stream: myStream,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: SizedBox(
height: 100, width: 100, child: CircularProgressIndicator()),
);
} else {
final docs = snapshot.data.docs;
bool hasDateTime = ????? <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
return ListView.builder(
itemCount: docs.length,
itemBuilder: (ctx, index) {
final currTask = docs[index];
return InkWell(
highlightColor: Theme.of(context).secondaryHeaderColor,
splashColor: Theme.of(context).secondaryHeaderColor,
onLongPress: () {
showModalBottomSheet<dynamic>(
isScrollControlled: true,
context: context,
builder: (bCtx) {
FocusManager.instance.primaryFocus?.unfocus();
return TaskOptions(_updateTaskDesc,
() => _updateHasImage(docs[index]), currTask);
},
);
},
child: Dismissible(
direction: DismissDirection.startToEnd,
key: UniqueKey(),
onDismissed: (_) async {
FirebaseFirestore.instance
.collection('tasks')
.doc(widget.uid)
.collection('mytasks')
.doc(currTask['id'])
.delete();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("${currTask['desc']} dismissed"),
action: SnackBarAction(
label: 'Undo',
onPressed: () {
FirebaseFirestore.instance
.collection("tasks")
.doc(widget.uid)
.collection("mytasks")
.doc(currTask['id'])
.set({
"desc": currTask['desc'],
"id": currTask['id'],
"isDone": currTask['isDone'],
"hasImage": currTask['hasImage'],
});
try {
FirebaseFirestore.instance
.collection("tasks")
.doc(widget.uid)
.collection("mytasks")
.doc(currTask['id'])
.update({
"dueDate": currTask['dueDate'],
"dueTime": currTask['dueTime'],
});
} catch (e) {}
},
),
),
);
},
child: ListTile(
...
subtitle: Text(hasDateTime
? DateFormat('dd/MM')
.format(DateTime.parse(currTask['dueDate']))
: ''),
...
I saw that a containsKey('key') method works for some people but I get NoSuchMethod when I try that. What can I do?

The single document is just a normal Dart Map, so you can check if a key exists or not using containsKey method.
So you condition becomes the following:
bool hasDateTime = currTask.containsKey('dueDate`);
NOTE: In the question I can see that you are defining the condition in the wrong place which is outside the itemBuilder method in the ListView so that it is not item based and well not work because it does not make sense.
You can have it in this place:
...
itemBuilder: (ctx, index) {
final currTask = docs[index];
bool hasDateTime = currTask.containsKey('dueDate`);
return InkWell(
...

Related

I'm creating an grocery app in Flutter with firebase but i am unable show the updated cart value to text widget

I'm creating an grocery app in Flutter with firebase but i am unable show the updated cart value to text widget.
This is my List view
var fire_storedb = FirebaseFirestore.instance.collection("vegetables").snapshots();
Container(
margin: const EdgeInsets.only(top: 2),
alignment: Alignment.center,
child: StreamBuilder(
stream: fire_storedb,
builder: ((context, snapshot) {
if (!snapshot.hasData) return const CircularProgressIndicator();
return (ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.vertical,
itemCount: snapshot.data!.docs.length,
itemBuilder: (context, index) {
return (grocery_list(snapshot, index, context,values45));
},
));
})),
),
Below is my grocery_list function which is called from ListView ........
Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
InkWell(
child: Icon(FontAwesomeIcons.minus),
onTap: () async {
String? grocery_id =
snapshot.data?.docs[index].reference.id;
FirebaseFirestore.instance
.collection("Cart")
.where("grocery_id", isEqualTo: grocery_id)
.get()
.then((value) {
value.docs.forEach((element) {
FirebaseFirestore.instance
.collection("Cart")
.doc(element.id)
.delete()
.then((value) {
print("Success!");
});
});
});
}), //Inkwell for delete item from cart
VerticalDivider(width: 10,), ////// Vertical Divider
VerticalDivider(width: 10,), ////// Vertical Divider
InkWell(
child: Icon(FontAwesomeIcons.plus),
onTap: () async {
SharedPreferences sharedPreferences =
await SharedPreferences.getInstance();
var email =
sharedPreferences.getString("email").toString();
String? docid =
snapshot.data?.docs[index].reference.id;
Map<String, String?> data_to_save = {
"grocery_id": docid,
"quantity": "1",
"email": email,
"name": snapshot.data!.docs[index]['name'],
"price": snapshot.data!.docs[index]['price'],
"si": snapshot.data!.docs[index]['si'],
"image": snapshot.data!.docs[index]['image'],
};
var collectionRef = await FirebaseFirestore.instance
.collection("Cart");
collectionRef.add(data_to_save);
},
), // Inkwell for add item to cart
],
),
I want to place the below code between the two vertical divider as a text wideget to show the no of items added to cart. Can someone help.? I'm able to get the cart value in cart_value but unable to display it to Text widget.
FirebaseFirestore.instance.collection("Cart").get().then((value) {
value.docs.forEach((element) {
FirebaseFirestore.instance.collection("Cart").doc(element.id).get().then((value2) => {
if(value2.data()!['grocery_id']==docid)
cart_value = (value2.data()['quantity'])
});
});
});
You should be using a Future method to fetch data from Firestore and return an integer or double value of cart_value like this :
int cart_value = 0;
Future<int> cart() async {
var cart = await FirebaseFirestore.instance.collection("Cart").get();
for (var element in cart.docs) {
FirebaseFirestore.instance.collection("Cart").doc(element.id).get().then((value2) => {
if(value2.data()!['grocery_id']==docid){
cart_value = (value2.data()!['quantity'])
}
});
}
return cart_value;
}
and put the Future method cart in the future of your FutureBuilder widget:
FutureBuilder(
future: cart(),
builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data!.toString());
}})

how can use future in the listview flutter?

I have future function and I want show this in the listview.seprator, but the listview do not get the future value. how can i fix this?
this is my code:
my hive class:
#HiveType(typeId: 3)
class TaskCat extends HiveObject{
#HiveField(0)
String catName;
#HiveField(1)
int userId;
#HiveField(2)
User? user;
TaskCat(this.catName,this.user,this.userId);
}
This is my function:
Future<List> showCategoryInHome() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
var taskCatBox = await Hive.openBox('taskCat');
var filtertaskCat = taskCatBox.values
.where(
(TaskCat) => TaskCat.userId == sharedPreferences.getInt('key'))
.toList();
return filtertaskCat;
}
and this is my listview code:
FutureBuilder(
future: controller.showCategoryInHome(),
builder: (context, snapshot) {
Future<List> test = controller.showCategoryInHome();
return ListView.separated(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount: 11 , // here currently I set the fix value but I want the length of my list
itemBuilder: (context, index) {
return TextButton(
onPressed: () {
},
child: Text(
test[index].[catName], // and here not working too bucouse the list is future
style: normalTextForCategory,
),
);
},
separatorBuilder:
(BuildContext context, int index) {
return const VerticalDivider(
width: 15,
color: Colors.transparent,
);
},
);
},
)
Try this:
FutureBuilder<List>(
future: controller.showCategoryInHome(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Text('Loading....');
default:
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
List data = snapshot.data ?? [];
return ListView.separated(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount:data.length,
itemBuilder: (context, index) {
return TextButton(
onPressed: () {},
child: Text(
data[index]['catName'],
style: normalTextForCategory,
),
);
},
separatorBuilder: (BuildContext context, int index) {
return const VerticalDivider(
width: 15,
color: Colors.transparent,
);
},
);
}
}
},
),
Inside your Future you have builder, where you can access to your future when it ready via snapshot.
I've added the precise type where to make the use of Futurebuilder easier.
Future<List<TaskCat>> showCategoryInHome() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
var taskCatBox = await Hive.openBox('taskCat');
var filtertaskCat = taskCatBox.values
.where(
(TaskCat) => TaskCat.userId == sharedPreferences.getInt('key'))
.toList();
return filtertaskCat;
}
And adjust your Futurebuilder to the following:
FutureBuilder<List<TaskCat>>(
future: controller.showCategoryInHome(),
builder: (context, snapshot) {
// Check if your future has finished
if(snapshot.hasData) {
// Here you have the result of your future, which is a List<TaskCat>
final tasks = snapshot.data;
return ListView.separated(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount: tasks.length,
itemBuilder: (context, index) {
return TextButton(
onPressed: () {
},
child: Text(
tasks[index].catName,
style: normalTextForCategory,
),
);
},
separatorBuilder:
(BuildContext context, int index) {
return const VerticalDivider(
width: 15,
color: Colors.transparent,
);
},
);
} else {
// Here you can show e.g. a CircularProgressIndicator
return SizedBox();
}
},
)

Flutter Multiple combined filter

hey i am new too flutter, i want to create combined filter screen alike in a e commerce app,for example product will have 3 field Brand,price range,size,i want to display data from firebase snapshot by combining, brand ,price and size
stream:
FirebaseFirestore.instance.collection("users").snapshots(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.active) {
final brandss = FirebaseFirestore.instance
.collection('users')
.where('name', isEqualTo: 'zara')
.snapshots();
if (snapshot.hasData && snapshot.data != null) {
return Expanded(
child: ListView.builder(
itemCount: snapshot.data!.docs.length,
itemBuilder: (context, index) {
Map<String, dynamic> userMap =
snapshot.data!.docs[index].data()
as Map<String, dynamic>;
return ListTile(
leading: CircleAvatar(
backgroundImage:
NetworkImage(userMap["profilepic"]),//image
),
title: Text(
userMap["brand"] + " (${userMap["price"]})"),
subtitle: Text(userMap["email"]),
trailing: IconButton(
onPressed: () {
// Delete
},
icon: Icon(Icons.delete),
),
);
},
),
);
} else {
return Text("No data!");
}
``` please help me with logic
you can try to filter 3 conditions with multiple where
FirebaseFirestore.instance.Collection('product').where('Brand', isEqualTo:Brand).where('price', isLessThanOrEqualTo: maxPrice).where('price', isGreaterThanOrEqualTo: minPrice).where('size',isEqualTo:size)

Firebase Basic Query for datetime Flutter

I am trying to write a program to check if the time selected by the user already exists in the firebase firestore or not. If it does then I navigate back to the page where they select time again.
But as of now, I am succeeded in sending the date and time to firebase and but not the latter part.
DateTime _eventDate;
bool processing;
String _time;
bool conditionsStatisfied ;
#override
void initState() {
super.initState();
_eventDate = DateTime.now();
processing = false ;
}
inside showDatePicker()
setState(() {
print('inside the setState of listTile');
_eventDate = picked ;
});
inside the button (SAVE):
onPressed: () async {
if (_eventDate != null) {
final QuerySnapshot result = await FirebaseFirestore
.instance
.collection('events')
.where('event_date', isEqualTo: this._eventDate)
.where('selected_time', isEqualTo: this._time)
.get();
final List <DocumentSnapshot> document = result.docs;
if (document.length > 0) {
setState(() {
print('inside the method matching conditions');
showAlertDialogue(context);
});
}else{
final data = {
// "title": _title.text,
'selected_time ': this._time,
"event_date": this._eventDate
};
if (widget.note != null) {
await eventDBS.updateData(widget.note.id, data);
} else {
await eventDBS.create(data);
}
Navigator.pop(context);
setState(() {
processing = false;
});
}
};
some guidance needed on how do I resolve this issue!
Also, because of the else statement now the program won't write the date into firestore.
After Alot of research, I came to realize that if you send the data from calendar in DateTime format then, because of the timestamp at the end of the Date it becomes impossible to match to dates. Hence I formatted the DateTime value into (DD/MM/YYYY).
Here is the rest of the code for reference:
class _AddEventPageState extends State<AddEventPage> {
String _eventDate;
bool processing;
String _time;
#override
void initState() {
super.initState();
// _eventDate = DateTime.now();
processing = false ;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Please select a date'),),
body: Column(
children: [
hourMinute30Interval(),
Text('$_time'),
ListView(
scrollDirection: Axis.vertical,
shrinkWrap: true,
children: <Widget>[
ListTile(
title: Text(
'$_eventDate'),
onTap: () async {
DateTime picked = await showDatePicker(context: context,
initialDate: DateTime.now(),
firstDate: DateTime(DateTime.now().year - 1),
lastDate: DateTime(DateTime.now().year + 10),);
if (picked != null) {
setState(() {
print('inside the setState of listTile');
_eventDate = DateFormat('dd/MM/yyyy').format(picked) ;
});
}
},
),
SizedBox(height: 10.0),
ListTile(
title: Center(
child: Text('Select time for appointment!', style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
),
),
processing
? Center(child: CircularProgressIndicator())
: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: Material(
elevation: 5.0,
borderRadius: BorderRadius.circular(30.0),
color: Theme
.of(context)
.primaryColor,
child:MaterialButton(
child: Text('SAVE', style: TextStyle(
fontSize: 20,
color: Colors.white,
fontWeight: FontWeight.bold,
)),
onPressed: () async {
if (_eventDate != null) {
AddingEventsUsingRajeshMethod().getAvailableSlots(
_eventDate, _time).then((QuerySnapshot docs) async {
if (docs.docs.length == 1) {
showAlertDialogue(context);
}
else{
final data = {
// "title": _title.text,
'selected_time': this._time,
"event_date": _eventDate,
};
if (widget.note != null) {
await eventDBS.updateData(widget.note.id, data);
} else {
await eventDBS.create(data);
}
Navigator.pop(context);
setState(() {
processing = false;
});
}
});
}
}
),
),
),
],
),
],
),
);
}
showAlertDialogue method :
showAlertDialogue(BuildContext context) {
Widget okButton = FlatButton(onPressed: (){
Timer(Duration(milliseconds: 500), () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => datePicker()),
);
});
}, child: Text(' OK! '));
AlertDialog alert = AlertDialog(
title: Text('Slot unavailable'),
content: Text('This slot is already booked please select another slot'),
actions: [
okButton,
],
);
showDialog(context: context ,
builder: (BuildContext context){
return alert ;
}
);
}
The hourMinute30Interval() is nothing but a Widget that returns a timePickerSpinner which is a custom Widget. Tap here for that.
The Query that is run after passing the _eventDate and _time is in another class, and it goes as follows :
class AddingEventsUsingRajeshMethod {
getAvailableSlots(String _eventDate , String _time){
return FirebaseFirestore.instance
.collection('events')
.where('event_date', isEqualTo: _eventDate )
.where('selected_time', isEqualTo: _time)
.get();
}
}
You can name it something prettier ;)

How to access an array of DocumentReference in flutter?

I want to access all the reg_events for the currently logged in user. I have the following code right now
stream: Firestore.instance.collection('users').document(email).snapshots(),
builder: (context, snapshot){
if(!snapshot.hasData){
return Text("Loading..");
}
return Center(
child: new Container(
child: new PageView.builder(
onPageChanged: (value) {
setState(() {
currentpage = value;
});
},
controller: controller,
itemCount: snapshot.data['reg_events'].length,
itemBuilder: (context, index) => builder(index, snapshot.data)),
),
);
}
),
The 'builder' is:
builder(int index, DocumentSnapshot document) {
return new AnimatedBuilder(
animation: controller,
builder: (context, child) {
double value = 1.0;
if (controller.position.haveDimensions) {
value = controller.page - index;
value = (1 - (value.abs() * .5)).clamp(0.0, 1.0);
}
return new Center(
child: new SizedBox(
height: Curves.easeOut.transform(value) * 200,
width: Curves.easeOut.transform(value) * 1000,
child: child,
),
);
},
child: new Card(
child: Text(document.data['reg_events'][0].toString(),
textAlign: TextAlign.center,
style: TextStyle(fontSize: 15, color: Colors.white),),
margin: const EdgeInsets.all(10.0),
color: index % 2 == 0 ? Colors.blue : Colors.red,
),
);
}
But it outputs "Instance of 'DocumentReference'". How do I access this Document Reference?
Maybe it not understand reg_event as List so try this,
stream: Firestore.instance.collection('users').document(email).snapshots(),
builder: (context, snapshot){
List regEvent = new List();
if(snapshot.hasData){
regEvent = snapshot.data['reg_events'];
}
if(!snapshot.hasData){
return Text("Loading..");
}
return Center(
child: new Container(
child: new PageView.builder(
onPageChanged: (value) {
setState(() {
currentpage = value;
});
},
controller: controller,
itemCount: regEvent.length,
itemBuilder: (context, index) {
print(regEvent[index]);
return builder(index, snapshot.data)),}
),
);
}
),
DocumentReference is like a pointer to one document. You can get the single document using .get method which returns Future<DocumentSnapshot>. Since you have an array of them, you can then use Streams to get a bunch of Futures.
List<DocumentReference> references = [ref, ref, ref];
var myStream = Stream.fromFutures(references.map((ref) => ref.get()).toList());
StreamBuilder(builder: ..., stream: myStream);
But...
Firestore has querying, so it should be better if you actually use it. You should be able to reference your reg_events like that:
Firestore.instance.collection('users').document("$email/reg_events").snapshots();
In this example a User object is created which contains a list of references of the entities (or events). This list is then passed to the DatabaseService class which returns a list of EntityDetails stream objects.
DatabaseService Class:
final CollectionReference entityCollection =
Firestore.instance.collection('entities');
final CollectionReference userCollection =
Firestore.instance.collection('user');
Stream<UserDetails> get userDetails {
return userCollection
.document(uid)
.snapshots()
.map(_userDetailsFromSnapshot);
}
UserDetails _userDetailsFromSnapshot(DocumentSnapshot snapshot) {
return UserDetails(
email: snapshot.data['email'],
phone: snapshot.data['phone'],
fname: snapshot.data['fname'],
lname: snapshot.data['lname'],
streetNr: snapshot.data['street_nr'],
city: snapshot.data['city'],
entities: List.from(snapshot.data['entities']));
}
List<Stream<EntityDetails>> getEntitiesFromDRList(
List<DocumentReference> entities) {
List<Stream<EntityDetails>> elist = new List();
entities.forEach((element) {
elist.add(element.snapshots().map((_entityDetailsFromSnapshot)));
});
return elist;
}
EntityDetails _entityDetailsFromSnapshot(DocumentSnapshot snapshot) {
return EntityDetails(
uid: uid,
name: snapshot.data['name'],
description: snapshot.data['description'],
type: snapshot.data['type'],
geoPoint: snapshot.data['geopoint'],
adressString: snapshot.data['adress_string'],
email: snapshot.data['email'],
phone: snapshot.data['phone'],
);}
Widget
stream: DatabaseService(uid: uid).userDetails,
builder: (context, snapshot) {
if (snapshot.hasData) {
UserDetails userDetails = snapshot.data;
//Get the Streams
DatabaseService(uid: uid)
.getEntitiesFromDRList(userDetails.entities)
.forEach((element) {
element.listen((data) {
print("DataReceived: " + data.name);
}, onDone: () {
print("Task Done");
}, onError: (error) {
print("Some Error");
});
});
User-Object
class UserDetails {
final String email;
final String phone;
final String fname;
final String lname;
final String streetNr;
final String city;
final List<DocumentReference> entities;
UserDetails(
{this.email,
this.phone,
this.fname,
this.lname,
this.streetNr,
this.city,
this.entities});
}

Categories

Resources