Do you need to use the "new" keyword in Dart? - dart

In my Dart based application I just noticed that I can omit the new keyword and everything works perfectly fine.
Instead of final widget = new Widget(); I can also use final widget = Widget();.
Does this have any effect in code?

No, it does not. With Dart 2 (click for the announcement with more information) the new and also const keywords were made optional.
This means that new Widget() does the exact same as Widget() on its own.
The const keyword can, however, change a value that would not be a const implicitly to a const.
So you will have to explicitly specify const when needed.

In Dart 2, if you invoke a constructor like a function, without a new or const in front, then it is equivalent to using new.
If you want a const invocation, then you should put const in front.
Inside a const expression, you don't need to write const again, and in some contexts that require const expressions (like switch case expressions and initializers of const variables), you don't even need the outer const.
So you don't ever need to write new.
Dart language team wants to allow expressions where you can insert either new or const and still have the invocation be correct (that is, a const constructor with constant arguments) to default to inserting const instead of new, hopefully in an early update to Dart 2.
For that reason, I recommend writing new it in front of Object(), or any other const constructor where you need the object to be a new instance. That's a very rare case, usually you don't care about the identity of your immutable object (which is why inserting const is considered a good idea). (That plan didn't pan out, so you can ignore this.)

The new keyword was made optional in Dart 2. As of now, calling a class will always return a new instance of that class. As per my recommendation, you can use it (NOT MANDATORY) outside of a Layout definition, but omit in inside Layouts.
One more point which I would like to share with you guys is that if you use new or const keyword while declaring widgets, you are also able to see the + icon which you can use to collapse and expand the widget body code. This is useful when you want to collapse/hide the rest widget code in dart file while working on another widget code in the same file.

Related

How to create a "constant reference" getter in Dart?

Say I have a class ListContainer that contains and manages a list that must be accessible from outside. Since managing this list is complicated, I don't want to let anyone other than ListContainer modify it. In C++, I would create a function that returns const reference, but in Dart, const works completely differently. Just using getter will not prevent someone from modifying the list.
So how can I provide an access to the list values without allowing to modify the list?
I'm looking for something better than creating a getNth function because that would also require creating methods like length, map, and so on.
I think UnmodifiableListView is what you are looking for.
check out UnmodifiableListView Documentation
you can use it like this:
List<int> _myList = [1, 2, 3];
UnmodifiableListView<int> get myList => UnmodifiableListView(_myList);

What's with the final/const craze in Flutter?

Java have final as well as Dart, but as far as I have seen, most Java people avoid using it all the time, since it can make your code less readable. For example, final is used all the time in class constants such as public static final int, but most people avoid using it in a method variable, since it's just seen as "excessive code correctness" by many developers, adding to boilerplate code.
C++ also has const and it can get crazy with it:
char ** const * const x // declare x as const pointer to const pointer to pointer to char
Now I am starting to learn Flutter and I am seeing final and const all over the place. Are those really necessary, like when they say:
Fields in a Widget subclass are always marked "final".
Or can they be treated as "excess of code correctness" and be removed?
Sorry if maybe my question is too stupid, I am really new to Dart and Flutter and I don't know all the side effects/benefits of using final and const, to justify the additional attention of when to remember to use them in my code.
const means that the value of the variable is known at compile time and it is going to be constant for the whole duration of the application.
Since the value is known at compile time, you can make the necessary optimisations.
final means that the value will be constant or immutable from the moment it is set. But it is set at runtime. So you don't know it at compile time and you can't optimise it.
If you don't use final you lose the immutability feature to what you should adhere in Flutter. You should always create a widget, not modify it. And the way to enforce that is to make all its fields final.
All these finals are not here just for fun. Flutter revolves around immutability. final is a neat way to enforce that immutability, ensuring you are correctly following the different design patterns.
They are definitely not "excess of correctness" no. They exists to assure a maintainable app. 2 characters is absolutely worth the effort
The main upside of using const is that, in a reactive UI like Flutter where large parts of the widget tree may be rebuilt regularly, every single object (and all of its own variables) of every single widget will need to be recreated on every rebuild, except if they are marked const, in which case the same instance will be reused throughout the lifetime of the app.
Even with a moderately complex UI this will quickly save thousands of object instantiations, which can be significant especially when animating widgets. So, it is considered a good practice to use const when possible.
final is different, it doesn't bring any performance benefits and is mainly a way to ensure that you are following Flutter design patterns. In my opinion it improves readability in the way that knowing quickly what is immutable and what is not can be very important when developing with Flutter.

What is the purpose of assigning `const` value to a `final` variable in dart? [duplicate]

This question already has answers here:
What is the difference between the "const" and "final" keywords in Dart?
(16 answers)
Closed 4 years ago.
So I was doing the first example for Flutter, and under
Step 4: Create an infinite scrolling ListView,
I encountered this piece of code:
class RandomWordsState extends State<RandomWords> {
final _suggestions = <WordPair>[];
final _biggerFont = const TextStyle(fontSize: 18.0);
...
}
But I found the following line a little spooky.
final _biggerFont = const TextStyle(fontSize: 18.0);
My question is, what is the purpose of assigning a constant value to a final variable?
I know that
Compile-time constants are canonicalized,i.e. no matter how many times
you write const MyObj(0, 0),you only create one object.
This may sound useful, but you can simply create the const variable to hold the value and use that variable instead.
Well, don't you think it's kinda redundant? I get it that the developers at Flutter wanted to create a compile-time constant object, but hey! you are assigning that value to a final variable. Which is somewhat the same thing.
Any thoughts?
UPDATE
I googled some definitions, I found that
const constructors cannot have a body and It's class must not have
any non-final fields
So is this the reason why we used the const keyword? Because if you'll look at the TextStyle class's design, you'll realize that they have done the exact same thing here.
I personally think
final _biggerFont = const TextStyle(fontSize: 18.0);
looks like a mistake, and that that alone is reason enough to change it.
The member is only used inside the same class, so there is no reason not to make it static. Then it will not take up one extra memory location for each instance of the class, all pointing to the same value. (That's assuming the compiler doesn't recognize the field as always having the same value, and just inlines the value everywhere).
If the member is static, it might as well also be const, so I'd write it as:
static const _biggerFont = TextStyle(fontSize: 18.0);
This assumes that the code is what I found by searching for final _biggerFont = const.
If there is a subclass in the same library which overrides _biggerFont, then it does need to be an instance variable. It could still be a getter instead of a field, then. Whether that's an efficiency improvement depends on how the class is used, and how well a compiler optimizes a final field that always has the same value.
In any case, creating a private instance member which always has the same constant value looks like something that should just be a static constant to begin with, and code that looks like a mistake is confusing to read. I'd rewrite it (or document it) just for that reason - to avoid the reader being confused about why it is the way it is.
const values are canonicalized.
This means no matter how often your code contains
final _biggerFont = const TextStyle(fontSize: 18.0);
there will only a single const TextStyle(fontSize: 18.0) instance.
Using const for class' fields requires static, this would not allow to access its value using a reference to an instance of RandomWordsState.
There are different preferences for classes with const constructors
http://dart-lang.github.io/linter/lints/avoid_field_initializers_in_const_classes.html
AVOID field initializers in const classes.
Instead of final x = const expr;, you should write get x => const
expr; and not allocate a useless field. As of April 2018 this is true
for the VM, but not for code that will be compiled to JS.
and top-level fields
http://dart-lang.github.io/linter/lints/prefer_const_declarations.html
PREFER using const for const declarations.
Const declarations are more hot-reload friendly and allow to use const
constructors if an instantiation references this declaration.
The IDE also suggests to replace final with const for local variables that are initialized with constant values
I haven't found where this suggestion comes from, but it makes sense because local variables can be const without static

Using "final" for a Class instantiation

I came across the following code the other day (below) and wondered if it achieves anything of significance in Dart other than the fact that the Class instantiation cannot be changed. I did read some SO posts regarding Java, however they didn't appear conclusive, and don't necessarily apply to Dart. I would not have coded it that way (with final), however perhaps I should. Is there any major significance to using "final" in this instance and what does it achieve?
import 'dart:math';
final _random = new Random();
From Dart: Up and Running:
If you never intend to change a variable, use final or const, either instead of var or in addition to a type. A final variable can be set only once; a const variable is a compile-time constant.
A local, top-level, or class variable that’s declared as final is initialized the first time it’s used.
So there are three benefits to using final here:
If some code erroneously tries to set _random another time, an error will be generated.
It is also clearer to other programmers (or the same programmer at a later date) that _random is never intended to be changed.
_random is not initialized until it used, so the application will start faster.
For those reasons, I would consider this a good use of final; certainly the code would "work" without it, but it's better this way.
In short, I think the book offers sound advice: "If you never intend to change a variable, use final or const".
From the documentation :
A local, top-level, or class variable that’s declared as final is initialized the first time it’s used. Lazy initialization of final variables helps apps start up faster.

What is the syntax for implicit cast operator in dart?

I would like to cast instances of my custom class A to int. What is the syntax of the implicit cast operator? (I thought I remembered that there is such a feature but I can't find it on the web)
int a = (new A());
You can also use as to help tell the tools "no, really, treat this object as this type".
A good example of this is when you have to deal with dart:html's querySelector() function.
FormElement form = querySelector('#sign-up') as FormElement;
In the above, the object returned by querySelector('#sign-up') is checked that it is really an instance of FormElement.
Learn more at https://www.dartlang.org/docs/dart-up-and-running/ch02.html#operators
Type annotations are not allowed to affect behavior in Dart. If you're not running in checked mode, then this:
int a = new A();
will work the same as this:
var a = new A();
at run-time. In other words, when not in checked mode, you're welcome to store your A in a variable annotated as an int, but no actual conversion takes place.
If you are running in checked mode, the first form will give you a runtime exception.
I'm not sure, but I think what you're asking for is a way to define a conversion between your class A and int that will happen automatically when "cast" to an int. No such thing exists, to my knowledge. You should simply define a method to do so. For example:
int a = new A().to_i();

Resources