0

I'm quite confused regarding Dart Constructors. What I am trying to do is having two parameters, both final but one is based on the other.

class Chart extends StatelessWidget {
  final List<Transaction> _recentTransactions;
  final double _totalAmount;
  Chart(List<Transaction> _recentTransactions)
      : this._recentTransactions = _recentTransactions,
        this._totalAmount =
            _recentTransactions.fold(0.0, (prev, next) => prev + next.price);
}

This code above works. I have a private list, and my private double _totalAmount is final but is based on the list _recentTransaction.

I've came up with this code reading the Documentation for final constructor

But I don't really understand why this won't work

class Chart extends StatelessWidget {
  final List<Transaction> _recentTransactions;
  final double _totalAmount;
  Chart(List<Transaction> _recentTransactions) {
    this._recentTransactions = _recentTransactions;
    this._totalAmount =
        _recentTransactions.fold(0.0, (prev, next) => prev + next.price);
  }
}

The difference pretty much is that on first implementation I use the :, and in second a normal {}

What am I missing here? As much as I understood the : is used to refer to a different constructor (that in this case I don't have).

I could also make the second example works not declaring final the _totalAmount, still, since the value won't ever change (and plus, since is in Flutter, I got a warning regarding that I should declare it final because my class extends a StatelessWidget that is declered as @immutable.

TL;DR: Why I can use a Constructor with : for final parameters but it doesn't work with a normal Constructor?

Tizianoreica
  • 2,142
  • 3
  • 28
  • 43

0 Answers0