Variables

 

Variables in dart are type-checked, which means that every variable must be declared with a specific type, and that type must match with what the variable is assigned throughout your programs.

Here are some basic types and examples:

String foo = 'foo';
int bar = 0;
double foobar= 12.454;
bool isCool = true;
List<String> foobarList = ['foo', 'bar'];

Dictionaries (which map keys to values) are specificed as the ‘Map’ type in dart. You have to specify the key type and the value type, like as follows.

Map<String, int> grades = {
  'John': 99,
  'Doe': 30,
};

You will get an error if you assign an incompatible type to the same variable.

String errorExample = 'foo';
errorExample = 2; // ERROR

You can use ‘var’ and ‘dynamic’ to make a variable type dynamic, but it is usually not a good idea to do this, as it could end up in frustrating errors down the line.

Additionally, dart has a unique ‘final’ and ‘const’ operator that can be used for declaring variables. ‘final’ is generally used to declare a variable that won’t change once it’s declared. For example, if a user types in their name and we save it to a variable, we know that variable (their name) won’t change, so we can initialize / declare it like so:

final String name;

The ‘const’ keyword is a little more of a specific use case – it makes the variable constant from compile-time only. It will be useful later down the line for the Flutter framework, but for now, don’t worry about ‘const.’

 

من moded

اترك تعليقاً