What is the function of the keys { } in this interpolation?

Asked

Viewed 389 times

5

class MyStateFull extends StatefulWidget{

  MyStateFull(this.nome);
  final String nome = 'Maria';

  @override
  _ContadorClique createState() => _ContadorClique();

  // @override
  // State<StatefulWidget> createState() {
  //   return _ContadorClique();
  // }
}

child: Text('$widget.nome')  // retorna MyStateFull.nome
child: Text('${widget.nome}) //retorna o valor da proprieadade
child: Text(widget.nome) //retorna o valor da proprieadade

In one of the above cases I can only access the value of the property if it is between keys, what is the function of the keys in this case?

2 answers

5


The key function is to avoid ambiguity. As in interpolation it is possible to use any valid expression in code in some situations it may be that the compiler does not know what to do and determine where the expression ended.

This is exactly what happened with the first case. He understood that the expression was only the word following the $, the rest would be text, because it could be text itself, as the compiler will know? The point encloses a token And so what he finds afterwards is considered normal text, which is not what he wants. The keys work as parentheses there grouping all the expression and indicating pro compiler that all that is one thing and only after closing the key is that it comes back have normal text to be printed without an evaluation.

Pro compiler the first case is as if written "${widget}.nome". Some languages require you to always have the keys to avoid confusion, because it’s just like you always have, only in some situations Dart puts the keys to you where he thinks you should, not necessarily where you wanted. I would standardize putting keys always even where there is no ambiguity.

Contrary to what the other answer says, although this has to do with interpolation, it’s not the keys that interpolate, it’s just a disambiguation mechanism, if it was interpolation then the first case would not interpolate at all and it does, Only the wrong way you wanted it. It also has nothing to do with dice type.

2

The function is to interpolate the string, without need to concatenate or convert data.

Take this example:

 print("O nome é ${widget.nome}");

Without the ${ would need to do so, concatenating with +:

 print("O nome é " + widget.nome);

Now imagine you have an entire "age" property, it would look like this:

 print("A idade é ${widget.idade}");

See that now, to concatenate string with integer, you need to convert:

 print("A idade é " + widget.idade.toString());

Therefore, interpolation using the prefix $ makes it simpler that.
If you want to see more about this, here’s the documentation of string Interpolation

  • who gave the downvote can explain the reason or is particular?

Browser other questions tagged

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