I have two textfields in my flutter app. I used showDatePicker on the first one when tapped and showTimePicker on the second one when tapped (to let a user choose a certain date and time).
I am using a class model to send and receive date and time both from one variable:
DateTime? taskDate; // Time as well
I thought about sending them separately but look what happens in firebase when I send them both together :
One timestamp field that has date and time seperated ( like a map).
My question is how can I point to one of them ( date or time) in Firestore so I can do some actions on them?
For example I want to add a task in 13 January 20203 and I want this to be saved in date field and the time to be saved in time field. What you see in the picture isn't picked date and time.
This is the code of sending data using a model and bloc state managment :
TaskModel? taskModel;
void addTask({
required String title,
required DateTime date,
}) {
emit(AddPostLoadingState());
taskModel = TaskModel(
taskTitle: title,
taskDate: date,
name: userModel!.name,
uid: userModel!.uId);
FirebaseFirestore.instance
.collection('tasks')
.add(taskModel!.toJson())
.then((value) {
getTask();
}).catchError((error) {
print(error);
emit(AddPostErrorState(error));
});
}
And since I know that datetime recieved as timestamp in firestore .. I changed it in the type when I get data :
void getTask() {
emit(GetTaskLoadingState());
FirebaseFirestore.instance
.collection('tasks')
.where('uid', isEqualTo: uId)
.orderBy('taskDate')
.get()
.then((value) {
tasks = []; // Global List<TaskModel>
for (var element in value.docs) {
data['taskDate'] = DateTime.fromMillisecondsSinceEpoch(
data['taskDate'].seconds * 1000);
tasks.add(TaskModel.fromJson(data));
}
emit(GetTaskSuccessState());
}).catchError((error) {
print(error.toString());
emit(GetTaskErrorState(error: error));
});
}
CodePudding user response:
The Firestore Timestamp
field is an atomic value that contains both date and time. There is no way to set the date and time of the field separately, as it's stored as a single value in the database.
If you want to manipulate the date and time separate in the database, consider storing them as separate fields (e.g. in a map as you already describe) yourself. Then you'll need to convert to/from a DateTime
in your code when reading from/writing to the database.