参数类型 'Object' 不能分配给参数类型 'Timestamp' - Flutter

时间:2021-06-22 18:14:31

标签: flutter object dart timestamp null-check

我有一个将“日期”作为最终参数的模型。

class WalletTransaction extends Equatable {
    final String id;
    final String amount;
    final String description;
    final bool isDepense;
    final Timestamp date;

  WalletTransaction(
     {required this.id,
     required this.date,
     required this.amount,
     required this.isDepense,
     required this.description});

我想传递这个模型类的一个实例,所以我做了一个空检查运算符来检查变量是否为空

AddWalletTransactions(
    new WalletTransaction(
        amount: amount ?? "00",
        date: date ?? Timestamp.fromDate(DateTime.now()),
        isDepense: isDepense ?? true,
        description: description ?? "",
        )
        )

但是它在 Timestamp.fromDate(DateTime.now()) 中给了我这个问题:

<块引用>

无法将参数类型“Object”分配给参数类型“Timestamp”。

1 个答案:

答案 0 :(得分:0)

错误(可能)出在您的 date 对象中。我还假设您使用的是来自 Timestampfirestore

在 Dart 中,如果 ?? 运算符为非空,则计算为左侧,否则为右侧。

但是,在计算该表达式的静态类型时,它只能选择双方都对其有效的类型。例如:

class Animal {}
class Dog extends Animal {}

final a = dog ?? Animal();
// a has a static type of Animal

final b = 'world' ?? 'hello';
// b has a static type of String

final c = Scaffold() ?? 'hello';
// c has a static type of Object

一般来说,Dart 会选择双方匹配的最具体的类型。在 Dog/Animal 示例中,Object 也是 a 的有效静态类型,但 Animal 也是如此,而 Animal 更具体,因此 {{1} } 被选中。

在您的示例中,您使用:

Animal

date ?? Timestamp.fromDate(DateTime.now()); 的静态类型是 Timestamp.fromDate(...),并且(我假设)Timestamp 的静态类型是 date

这 2 种类型根本不相关,因此对两者都有效的最具体类型是 DateTime,因此 Dart 为该表达式提供了静态类型 Object

如果您想从一个可能为也可能不为空的日期创建一个 Object,您只需将 Timestamp 移动到 ?? 中:

Timestamp

或者您可以使用具有 2 个 date: Timestamp.fromDate(date ?? DateTime.now()) 实例的三元运算符:

Timestamp

IMO 第一个选项稍微干净