Home > Back-end >  What keyword should variables in functions have in Dart?
What keyword should variables in functions have in Dart?

Time:11-17

I know how to name variables in classes but how does it relate to functions? I've noticed that some devs use in functions final keywords for variables that never change, but the others use var even in them.

Which of the following examples is the best? I mean in terms of clean code and speed

 doSomething() {
    final int i = 1;
    print(i.toString());
  }

   doSomething() {
    final i = 1;
    print(i.toString());
  }

  doSomething() {
    int i = 1;
    print(i.toString());
  }

  doSomething() {
    var i = 1;
    print(i.toString());
  }

CodePudding user response:

According to the official Dart documentation, using final vs var is a matter of taste; the important part is to be consistent. According to this answer, most compilers will notice that a variable is never reassigned whether or not you make it final. The same documentation link says that most variables should not have a datatype explicitly assigned, just the keyword final or var. I personally disagree because of bad experiences with accidentally retyping variables, but that is the official recommendation.

If you make the variable final, then the compiler will enforce its status as read-only. The linter recommends that you always use final for variables that aren't reassigned.

CodePudding user response:

Should I use var or type annotation such as int?

Here's my approach:

In Dart, The var keyword is used to declare a variable. The Dart compiler automatically knows the type of data based on the assigned variable because Dart is an infer type language.

So, if you know the type before, you can use var, since Dart can infer the type for you automatically. For example:

var name = 'Andrew'  

However, if you don't know the type before, you can use type annotation:

int age;
...
age = 5;
  • For more explanation, you can take a look at https://www.javatpoint.com/dart-variable at the "How to Declare Variable in Dart" section, they explain the answer to your question in greater detail, (I have used their example)

CodePudding user response:

It's preferable to use final for values that don't change.

And use linter if you are not sure.

  • dart pub add lints - official lints
#analysis_options.yaml
include: package:lints/recommended.yaml
  • dart pub add zekfad_lints - lints I like to use
#analysis_options.yaml
include: package:zekfad_lints/untyped/dart.yaml

# If you are using flutter
#include: package:zekfad_lints/untyped/flutter.yaml
  • Related