What is the meaning of the operator ":" after a Builder on Dart?

Asked

Viewed 100 times

1

I’m trying to understand and adapt a code. I’d like to know what this syntax means:

EditMyModelScreen(MyModel p) : editing = p != null, mymodel = p != null ? p.clone() : MyModel();

In particular, I would like to know what the "colon" means after the constructor and if there is a way to define another Editmymodelscreen, beyond the already defined.

1 answer

5


This is a variable initialization list. It is instructing you how to initialize class properties EditMyModelScreen based on the parameter passed in the constructor.

The following code:

EditMyModelScreen(MyModel p) : 
                               editing = p != null, 
                               mymodel = p != null ? p.clone() : MyModel();

Is equivalent to:

EditMyModelScreen(MyModel p) {
    editing = p != null;
    mymodel = p != null ? p.clone() : MyModel();
}

That is, it is a convenience to write the initialization of variables editing and mymodel more succinctly.

[...] and whether there is a way to define another Editmymodelscreen, in addition to the already defined.

If you refer to making another constructor, there is yes. A class can have as many constructors as you wish, just give one name different to this builder:

class EditMyModelScreen{
    EditMyModelScreen(MyModel p) : editing = p != null, mymodel = p != null ? p.clone() : MyModel();

    EditMyModelScreen.OutroConstrutor(){
        //Este construtor pode ser chamado com EditMyModelScreen.OutroConstrutor();
    }
}

For more information, read here (in English).

Browser other questions tagged

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