简体   繁体   中英

How can I send and receive two types of data from one single field in firestore for flutter?

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));
    });
  }

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 (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM