Reputation: 21
I just wanna know about this functionalities and what's effects if we don't use this on every single projects. Thanks for the explanation before.
Example:
int number = 2;
bool isTrue = true;
double floatNumber = 2.1;
Why we not use like this?
var number = 2;
var isTrue = true;
const floatNumber = 2.1;
Upvotes: 2
Views: 800
Reputation: 657731
There are various related Dart style guide rules
PREFER type annotating public fields and top-level variables if the type isn’t obvious.
CONSIDER type annotating private fields and top-level variables if the type isn’t obvious.
So for example for local variables the style guide even suggests to omit type annotations. The scope of the type annotations is limited to the function/method so the risk is low that inferred types can cause confusion.
For other situations the style guides suggests to add type annotations to avoid ambiguity.
There was a recent addition to Dart that allows to use integer literals to initialize double variables. This only works if the type annotation is added.
var val = 1;
print(val);
1
double val = 1;
print(val);
1.0
This example isn't too practical, because the feature is mostly used to pass literal double values to function/method/constructor parameters, but it demonstrates that the context is important for the decision when to explicitly specify the type using type annotations and when it is safe to omit.
There are also various linter rules that help to stay consistent.
Upvotes: 5