When is it recommended to Initialize a final property in the Class constructor?

Asked

Viewed 482 times

1

The example below is a summary of the original (Bringing it all Together) found on the official Flutter page.

On the first call, the class Cart is initialized by the constructor and in the second Cart2, nay.

As you notice the result is exactly the same, so I was in doubt, it is just a 'gurmetization' of the code or has some advantage/recommendation to initialize a property in the class constructor?

class Produto {
  const Produto({this.nome});
  final String nome;
}

void main() {
  Cart(produto: Produto(nome: 'Hd 1TB'), disponivel: true);
  Cart2(produto: Produto(nome : 'Hd 2TB'), disponivel: false);
}

class Cart {
  final Produto produto;
  final bool disponivel;
  Cart({Produto produto, this.disponivel}) : produto = produto 
  {
    print('Produto: ' + produto.nome);
    print('Disponível: ' + disponivel.toString());
  }  
}
/*
   Resultado:
   Produto: Hd 1TB
   Disponível: true
   Produto: Hd 2TB
   Disponivel: false
*/
class Cart2 {
  final Produto produto;
  final bool disponivel;
  Cart2({this.produto, this.disponivel})
  {
    print('Produto: ' + produto.nome);
    print('Disponivel: ' + disponivel.toString());
  }  
}

2 answers

2

The second is syntax sugar of the first, and in fact the second parameter of the first is still a syntax sugar and will occur with it the same as with the other parameter.

This syntax placing the this in the parameter indicates that you want it to automatically be assigned to the field with the same name.

The fact that final is irrelevant to this specific issue, it only makes a difference if you try to initialize the field within the constructor, then it becomes a problem because the initialization needs to occur before any processing.

The term property is mistaken, in the documentation they use the term instance variable (at some point they even use the term property generically in some ambiguous way, which indicates that the documentation is not good or the language itself is not well defined, which is scary). In some documents I saw the use of the term field. Something generic on the subject can be read at another answer from me.

  • Wonder what term to use, I saw here (https://dart.dev/guides/language/language-tour) the following: Dart supports top-level variables, as well as variables tied to a class or object (static and instance variables). Instance variables are sometimes known as fields or properties.

  • "This syntax putting this..."is referring to named arguments?

  • 2

    no, I’m talking about the parameters, in the case of builders.

2


When you use the class shape Cart you can perform validations.

When using the : initialized "Initializing Lists" that are expressions executed before constructs of superclass, are also executed before executing the constructor class Cart, so this form is normally used to check the parameters passed to the constructor class, so you can make changes to this parameter before finally setting its value to the variable final which cannot be modified after the constructor be executed.

Source: insert link description here

In the case of your example, it’s just two different ways of doing it or as you said "gurmetization".

I prefer to use the shape of Cart2 as it saves processing and is a cleaner way.

EDITED

You can validate for example the amount of items for display

class Cart {
  Cart(bool limitItens, int itensToDisplay)
      : limitItens = limitItens,
        itensToDisplay = limitItens ? 10 : itensToDisplay;

  final int itensToDisplay;
  final bool limitItens;
}

In the example it is validated if the limitItens is true, so if true is limited to a quantity of 10 items for display. Each parameter of constructor is separated by comma also after the ":"

Source: https://stackoverflow.com/a/54981594/10145630

Note: I am without Flutter here at the moment to give more complete examples.

  • ...você pode realizar validações. Of what type? Could exemplify?

  • 1

    @rubStackOverflow Check the section EDITED, added an example of validation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.