Search code examples
flutterobjectdarttimestampnull-check

The argument type 'Object' can't be assigned to the parameter type 'Timestamp' - Flutter


I have a model who have "date" as a final parameter .

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

I want to pass an instance of this model class so i did a null check operator to check if the variables is null or not

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

But the it gives me this problem in Timestamp.fromDate(DateTime.now()) :

The argument type 'Object' can't be assigned to the parameter type 'Timestamp'.


Solution

  • The error (probably) lies in your date object. I'll also assume you're using Timestamp from firestore.

    In Dart, the ?? operator is evaluates to the left-hand-side if it is non-null, otherwise the right hand side.

    However, when calculating the static type of that expression, it can only choose a type that both sides are valid for. For example:

    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
    

    In general, Dart chooses the most specific type that both sides match. In the Dog/Animal example, Object would also be a valid static type for a, but so is Animal, and Animal is more specific, so Animal is chosen.

    In your example, you use:

    date ?? Timestamp.fromDate(DateTime.now());
    

    The static type of Timestamp.fromDate(...) is Timestamp, and (I'm assuming) the static type of date is DateTime.

    These 2 types are not related at all, and so the most specific type that is valid for both is Object, so Dart gives that expression a static type of Object.

    If you want to create a Timestamp from a date that may or may not be null, you can simply move the ?? inside the Timestamp:

    date: Timestamp.fromDate(date ?? DateTime.now())
    

    or you can use a ternary operator with 2 Timestamp instances:

    date: date == null ? Timestamp.now() : Timestamp.fromDate(date)
    

    IMO the first option is slightly cleaner