Fuadit Muhammad
Fuadit Muhammad

Reputation: 21

What's for type declaration the variable in Dart? What reason we recommend it?

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

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657731

There are various related Dart style guide rules

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

Related Questions