【问题标题】:The argument type 'DateTime' can't be assigned to the parameter type 'Timestamp'参数类型“日期时间”不能分配给参数类型“时间戳”
【发布时间】:2021-08-31 12:06:34
【问题描述】:

我正在使用 Firebase 和 Flutter,并希望存储一个截止日期的值,但我收到了相互冲突的消息,这不允许我以我希望的格式存储它

型号 导入'package:cloud_firestore/cloud_firestore.dart';

class Task {
  final String id;
  final Timestamp due;


  Task({
    this.id,
    this.due,
  });

  factory Task.fromDoc(DocumentSnapshot doc) {
    return Task(
      id: doc.data()['id'],
      due: doc.data()['due'],
    );
  }
}

写入数据

DateTime _date = DateTime.now();
  TextEditingController _dateController = TextEditingController();

void _selectDate() async {
    final DateTime newDate = await showDatePicker(
      context: context,
      initialDate: _date,
      firstDate: DateTime.now(),
      lastDate: DateTime.now().add(Duration(days: 90)),
      helpText: 'Select date for task',
    );
    if (newDate != null) {
      setState(() {
        _date = newDate;
        _dateController.text =
            DateFormat("E, d MMM yyyy").format(_date).toString();
      });
    }
  }

TextFormField(
                                controller: _dateController,
                                onTap: _selectDate,
                                enabled: true,
                                readOnly: true,
                                decoration: InputDecoration(labelText: 'Date'),
                              ),

Task task = Task(budget: _sliderValue, due: _date);
          DatabaseService.updateDate(taskId: _taskId, task: task);

  static void updateDate({String taskId, Task task}) {
    DocumentReference taskRef = tasksRef.doc(taskId);
    tasksRef.get().then((doc) {
      taskRef.update({
        'due': task.due,
        'budget': task.budget,
        'status': 'open',
      });
    });
  }

【问题讨论】:

    标签: flutter datetime google-cloud-firestore datepicker timestamp


    【解决方案1】:

    以下行显示_date被定义为DateTime

    DateTime _date = DateTime.now();
    

    在这里,您尝试将 _date 传递给 Task 构造函数以获取 due 属性:

    Task task = Task(budget: _sliderValue, due: _date);
    

    但是,Taskdue 属性必须是 Timestamp

    class Task {
      final String id;
      final Timestamp due;
    
    ...
    

    要修复错误,您需要使用Timestamp.fromDate()DateTime 转换为Timestamp

    Task task = Task(budget: _sliderValue, due: Timestamp.fromDate(_date));
    

    【讨论】:

      【解决方案2】:

      试试下面的代码,我已经使用了这个代码,它对我有用

      DateTime dateTime =  DateTime.tryParse(/*Your date */);
      

      【讨论】:

      • 是的,现在它认为它是一个字符串不起作用。感谢您的尝试
      【解决方案3】:

      Firestore 将日期存储为 TimestampTimestamp 类有一个 toDate 方法:

      final date = timestamp.toDate();

      现在您的日期为DateTime

      【讨论】:

      • 这可以渲染日期,但在这种情况下没有帮助,因为它的日期选择器需要是 DateTime
      猜你喜欢
      • 2022-01-01
      • 2021-09-06
      • 1970-01-01
      • 2019-07-29
      • 1970-01-01
      • 2021-01-05
      • 2018-12-26
      • 2021-06-19
      • 2021-12-13
      相关资源
      最近更新 更多