How to list Firebase data filtered by date? - flutter

I want to list firebase data on page filtered by date
DatePicker to select date:
{
DateTime? pickedDate = await showDatePicker(
context: context,
locale: const Locale("tr", "TR"),
initialDate: DateTime.now(),
firstDate: DateTime(2000),
lastDate: DateTime(2100),
);
if (pickedDate != null) {
print(pickedDate);
String formattedDate = DateFormat('dd.MM.yyyy').format(pickedDate);
print(formattedDate);
setState(() {
tarihfiltre.text = formattedDate;
tarih = pickedDate;
});
}
}
Here is the code I wrote for these other filters:
FirestoreListView<Map<String, dynamic>>(
shrinkWrap: true,
query: FirebaseFirestore.instance.collection('odemeler'),
itemBuilder: (context, snapshot) {
Map<String, dynamic> odeme = snapshot.data();
if (searchString == '' ||
odeme['firma'].toString().toLowerCase().contains(searchString.toLowerCase()) ||
odeme['alici'].toString().toLowerCase().contains(searchString.toLowerCase()) ||
odeme['odeme'].toString().toLowerCase().contains(searchString.toLowerCase()) ||
odeme['bitis'] == tarih) {
return Column(children: [
const SizedBox(height: 10),
// Expanded(
// child: FutureBuilder(
// // Our existing list code
// ),
// ),
SizedBox(...
...)
odeme['bitis'] == tarih)
The above line is the code I tried for filtering by date, but it doesn't work.
How can I specify and list the data that is on the same date as the date I selected from the calendar?

You can use orderBy or Where clause to filter your data from firestore.
According to this link you should use the where method. Combine that with firebase flutter docs (relevant example here), you should be able to accomplish this using something like:
FirebaseFirestore.instance
.collection('odemeler')
.where('bitis', isEqualTo: 'tarih')
.where(...) //another where condition

Related

How to delete documents that contain a certain value in one of the fields. Firestore, Flutter

enter image description here
I have these documents, which contain data about each task I add to the list in my app.
child: StreamBuilder(
stream: _tasks.snapshots(),
builder: (context, AsyncSnapshot<QuerySnapshot> streamSnapshot) {
if (streamSnapshot.hasData) {
return ListView.builder(
itemCount: streamSnapshot.data!.docs.length,
itemBuilder: (context, index) {
final DocumentSnapshot documentSnapshot =
streamSnapshot.data!.docs[index];
return GestureDetector(
onLongPress: () => _update(documentSnapshot),
child: ListTile(
)
);
},
);
}
return const Center(
child: CircularProgressIndicator(),
);
},
),
I am using a stream builder to build the list. Each of the tasks have a checkmark and when i click it, It updates the value in firestore inside the IsDone field accordingly. I want to click a button outside the stream builder to delete the checked tasks. How do I loop through all the documents and find all the documents that contain the value true and delete them?
I tried this but im doing doing something wrong and it isnt changing anything:
void _delete() {
var docs = _tasks.doc().snapshots();
docs.forEach((doc){
if(doc.data()==true){
_tasks.doc(doc.id).delete();
}
});
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('You have successfully deleted a product')));
}
var datas = await FirebaseCalls.firebaseFirestore
.collection("collection_id")
.where("status", isEqualTo: true)
.get();
datas.docs.forEach((element) {
FirebaseFirestore.instance
.collection("collection_id")
.doc(element.id)
.delete();
});
or you can do like this as well.
var datas =
await FirebaseCalls.firebaseFirestore.collection("collection_id").get();
datas.docs
.where((element) => element["status"] == true)
.toList()
.forEach((el) {
FirebaseFirestore.instance
.collection("collection_id")
.doc(el.id)
.delete();
});
You can delete by doing this below:
find the particular document as per your query and get its document and collection ID.
FirebaseFirestore.instance
.collection("collection_id")
.doc("doc_id")
.delete();

I wants to show selected date in date picker when I tap again on date picker using flutter

Currently initialDate is set to DateTime.now() initially today's date must shown but when I select any date and again opens the Date Picker initial date should be the one which I have selected previously.
How to do this:
child: TextField(
onTap: () async {
DateTime? pickedDate = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(
1991), //DateTime.now() - not to allow to choose before today.
lastDate: DateTime(2025),
// onConfirm:widget.onChanged,
).then((pickedDate) {
if (pickedDate != null) {
// print(
// pickedDate); //pickedDate output format => 2021-03-10 00:00:00.000
String formattedDate =
DateFormat('yyyy-MM-dd').format(pickedDate);
print(formattedDate);
setState(() {
startDtcontroller.text = formattedDate;
//set output date to TextField value.
});
//print(startDtcontroller.text);
//formatted date output using intl package => 2021-03-16
//you can implement different kind of Date Format here according to your requirement
// DateFormat df = new DateFormat("yyyy-MM-dd");
// String stDate = df.format(pickedDate);
// print(stDate);
widget.onChanged(formattedDate);
} else {
print("Date is not selected");
}
});
You need to save that value somewhere...
DateTime? selectedDateTime;
...
child: TextField( onTap: () async {
DateTime? pickedDate = await showDatePicker(
context: context,
initialDate: selectedDateTime ?? DateTime.now(),
...).then(pickedDate) { setState(() => selectedDateTime = pickedDate);}

How can i check if a firebase realtime database value exists already? (FLUTTER/DART)

`
Expanded(
child: StreamBuilder(
stream: taskRef != null ? taskRef!.onValue : null,
builder: (context, snapshot) {
if(snapshot.hasData && !snapshot.hasError && data1!="null"){
final snapshot2 = Map<String, dynamic>.from(
((snapshot.data! as DatabaseEvent).snapshot.value??{}) as Map);
if(snapshot2 == null){
return Center(child: Text("No tasks added yet", style: TextStyle(color: Colors.amberAccent,
fontSize: 18),),);
}else{
Map<String, dynamic> map = Map<String, dynamic>.from(snapshot2);
var tasks = <Task>[];
for(var taskMap in map.values){
Task task = Task.fromMap(Map<String, dynamic>.from(taskMap));
tasks.add(task);
}
return ListView.builder(
shrinkWrap: true,
itemCount: tasks.length,
itemBuilder: (context, index){
Task task1 = tasks[index];
return Container`
This is a part of my realtime firebase database...for only one user in this photo.
The code that i used to show the tasks in my app. Should i do the same thing for my problem? The db has userId -> day -> taskId -> informations. When I insert in my DB a new Task (all the information) I want to check first if the startTime already exists. How is this possible? It confuses me because of the random taskId child.
taskRef = FirebaseDatabase.instance.ref().child(uid).child("images").child("MONDAY");

Flutter - Filter Stream based on Date picked

I have a simple flutter application where I retrieve a bunch of records from Firebase. The records contain a field called DATE, which is in DateTime format.(Date + time + TZ)
But from my application, How can I make a page where I can filter the records just for a selected DATE.
When I use .where('time', isGreaterThan : _selectedDate) , it works. But it gives all days after the selected date. I just want to filter for just ONE selected day.
Heres my Code:
Stream<QuerySnapshot> _getCurrentOders() async* {
yield* FirebaseFirestore.instance
.collection('ItemList')
.where('time', isGreaterThan: _selectedDate)
.orderBy('time', descending: false)
.snapshots();
}
I also use a DateTime picker to select a date.
DateTimeField(
initialValue: DateTime.now(),
onChanged: (val) {
setState(() {
_selectedDate = val;
});
},
format: format,
onShowPicker: (context, currentValue) {
return showDatePicker(
context: context,
firstDate: DateTime(2019),
initialDate: currentValue ?? DateTime.now(),
lastDate: DateTime(2100));
},
),
Thank you for the support!
// this gives you the first millisecond of the day
var startOfTheDay = DateTime(_selectedDate.year, _selectedDate.month, _selectedDate.day);
//and this gives you the first millisecond of the next day
var endOfTheDay = startOfTheDay.add(Duration(days: 1);
and after that you can use:
.where('time', isGreaterThan : startOfTheDay).where('time', isLessThan : endOfTheDay)

Flutter How to apply search filter in a querysnapshot used in Listview builder

This is my firebase data request code
and this is my future builder based on the qn.docs
How to search within the snapshot and ListView.builder to use the filtered set.
previously I was using a Local List and used to search as on Itemchanged
thanks in advance for your guidance.
I am new to flutter. so please explain with an example
Future <QuerySnapshot> getSpeakernames() async {
QuerySnapshot qn = await
FirebaseFirestore.instance.collection('speakernames').orderBy('speakername').get();
return qn;
}
Center(
child: Container(
child: ListView.builder(
itemCount: snapshot.data.docs.length,
itemBuilder: (BuildContext context, int index) {
DocumentSnapshot data = snapshot.data.docs[index];
return ListTile(title: Text(data.get("speakername")),
subtitle: Text(data.get("speakerdegree")), )
onItemChanged(String value) {
setState(() {
data.get("speakername").
newspeakernames = speakernames
.where((string) =>
string.toLowerCase().contains(value.toLowerCase()))
.toList();
});
}
you can use ".Where" property of Firestore
like below
Future <QuerySnapshot> getSpeakernames() async {
QuerySnapshot qn = await FirebaseFirestore.instance.collection('speakernames')
.where('speakername' , isEqualTo : SubramanianV).orderBy('speakername').get();
return qn;
}
You can use isGreaterThanOrEqualTo.
Example:
class doctorName {
getDoctorByName(String doctorName, String last) async {
return await Firestore.instance
.collection("Doctor")
.where("name", isGreaterThanOrEqualTo: doctorName)
.where("name", isLessThan: last)
//.where("name", isEqualTo: doctorName)
.getDocuments();
}
}