Home > database >  Flutter Dart: Dynamic Relationship inside Model Class Field
Flutter Dart: Dynamic Relationship inside Model Class Field

Time:12-23

I've used Laravel, where we can define relationships inside the model itself. So is that possible in Dart/Flutter?

I've built this Cart Model where Grand-total should be dynamic. So whenever I create an instance of this Cart Model, grand total will be auto-calculated once we enter the total & discount. until then the default value 0.

enter image description here

code from the image above:

class Cart {
  Cart({
    this.total = 0,
    this.discount = 0,
    this.grandTotal, // I want this field dynamic: (grandtotal = total - discount)
  });

  int total;
  int discount;
  int? grandTotal;
}

CodePudding user response:

define a getter method to calculate grandTotal.

Sample code:

int? get grandTotal {
    // TODO: check for null cases here
    return total - discount;
}
  • Related