Reputation: 31
I come from Javascript's "let", and I am a bit confused on what the big differences are between var and other types. I understand that there are some cases where we need to use var(anonymous data types), and some where we need to use explicit types. I also understand that the var is less concise and the types are more, but is there a more in depth or practical application of using types instead of var within Flutter development?
Upvotes: 3
Views: 1110
Reputation: 90095
You never need to use var
; you always can choose to specify an explicit type instead.
var
is used if you want to declare a variable and want the type to be inferred from the initializer. (If there is no initializer, the variable will be of type dynamic
. However, since dynamic
disables static type checking for that variable and incurs an extra runtime cost, you should avoid dynamic
when possible and should explicitly variables as dynamic
when it's necessary.
If the variable type is inferrable, whether you use implicit or explicit types is a matter of style.
Advantages of using explicit types:
Advantages of using implicit types:
List someList = [1, 2, 3];
actually declares someList
to be of type List<dynamic>
even though the right-hand-side would otherwise be inferred as List<int>
.Upvotes: 6
Reputation: 101
You have
var Multiple asignment and Dynamic type. It can be assigned from expressions of different types. Be careful, Dart will infer the correct type, as long as variables are declared and initialized at the same time if you are using var.
final Single assignment. It is often used for when declaring properties inside widget classes.
const Compile time constant.
Prefer const over final when possible.
Upvotes: 2
Reputation: 31259
Dart is a statically typed language so Dart needs to be able to determine the type at some point. But it is also smart enough to automatically determine the type based on the context. E.g. the type of the returned value from a function.
It is really a question about style but personally I think the type should be specified for method signatures and class variables. For all variables inside a method, I will use var/final and use clear variable names.
Another reason I try use var/final as much as possible is this can prevent some nasty issues with e.g. generics (List list = <String>['test']
makes list
variable the type List<dynamic>
.
dynamic
in Dart is really just saying to the compile "just let this pass and check if the program makes sense at runtime". So we really don't want to have much dynamic
in our code base since we are then using the compilers ability to statically check your program makes sense.
Upvotes: 2