Understanding Dart Variables and Data Types

Understanding Dart Variables and Data Types

A Beginner's Guide to Variables and Data Types

Dart is a versatile and modern programming language known for its ability to create web and mobile applications. Knowing variables and data types is essential as you explore the world of Dart. Just like in any programming language, variables act as the building blocks of your code, allowing you to store, manipulate, and work with data. Meanwhile, data types define the kind of information that variables can hold. Dart variables and data types will be thoroughly examined in this article, along with their importance and useful examples.

Variables

Variables are similar to labels or containers that let you work with and store data. Variables can hold text, numbers, objects, and other kinds of data stored as values. Within the logic of your program, you can use, modify, or manipulate these values as necessary.

Variable Declaration

In Dart, you have two options for declaring variables:

  • Explicit Type Declaration: Specify the variable's data type, followed by the variable name, to declare it. For example, to declare a string variable named "address" and initialize it with a value, you can use the following code:

      String address = "21 Brook Street";
    

    In the above example, String is the data type, indicating that the variable will hold a text (string) value, address is the variable name, and 21 Brook Street is the initial value assigned to the variable. This approach enforces the variable's data type.

  • Type Inference: In programming, type inference allows the compiler or interpreter to determine a variable's data type based on the value it holds. In Dart, when you use the var, final, or const keyword to define a variable without specifying the data type, the Dart compiler automatically reads the variable's value and determines its type.

      var address = "21 Brook Street";
    

    In this case, the Dart compiler determines that the variable address is of type String because it's initialized with a string value.

The var keyword

The var keyword enables you to create variables that can be changed or reassigned. Once you've declared a variable with var, you have the flexibility to reassign it with values of compatible or identical types. This flexibility in reassignment is a key feature of var-declared variables.

For instance, when you declare a variable using var like:

var address = "21 Brook Street";

Dart infers the type as String, allowing you to reassign it with another string because of the maintained type consistency. However, if you attempt to reassign it with a value of a different type, like:

address = 21;

would not be allowed as Dart enforces strong typing, ensuring that variables maintain their initially inferred type throughout their lifecycle.

The const keyword

In Dart, you can use the const keyword to declare a data value, and the program will keep that value in memory as a constant throughout its execution.

When you declare a variable using the const keyword, such as:

const address = "21 Brook Street";

This variable is treated as a constant by Dart, and the value assigned to it cannot be changed after initialization. In this case, address is a constant string with the value 21 Brook Street and it cannot be reassigned to a different value later in your code.

For example, when attempting to reassign a const variable like this:

address = "103 Bakers Street";

an error will be encountered because address has been declared as a constant, and the reassignment of const variables is not permitted by Dart. The value assigned to a const variable must be known at compile-time and cannot be altered during runtime.

The final keyword

The final keyword operates in the same way as the const keyword, allowing data values to be assigned only once. However, it's important to note that final values are not regarded as compile-time constants. Rather, they are set up during runtime and cannot be changed once that initial assignment has been made.

The final keyword in Dart addresses variables rather than actual objects. A variable that is declared as final cannot have its reference changed to point to a different object after it has been initially assigned. The variable’s reference is fixed. However, you can still alter the content of the object that the final variable points to if it is mutable, meaning that its elements or properties can be altered.

Consider a list example:

final List numbers = [1, 2, 3, 4];

In this case, the variable numbers is declared as final. This means you cannot change the reference to a different list. However, you can modify the content of the list by adding, removing, or updating its elements.

numbers.add(5); // This is allowed and adds 5 to the list
numbers.removeAt(2); // This is allowed and removes the element at index 2
numbers[0] = 10; // This is allowed and updates the first element to 10

It's important to note that trying to do the same with a const variable will result in an error, as const variables are truly immutable and do not allow changes to the content or reference.

Null safety

Dart incorporates null safety as a crucial feature to proactively prevent errors resulting from unintentional access to variables lacking a value. In Dart, the term "null" signifies the absence of a value for a variable. Null isn't merely an absence of a value; it represents a distinct value in itself. You have the ability to assign the value null to a variable, signifying that it presently lacks meaningful data.

To indicate that a variable can accept the null value, you append a ? to the variable's data type. This notation allows nullable variables to either contain a value of the specified type or be assigned the value null. Here's an example:

String? address; // Declaring a nullable string variable
address = "21 Brook Street"; // Valid assignment of a string value
address = null; // Valid assignment of the null value

In the example above, we declare address as a nullable string with the type String?, signifying its ability to store a string value or be set to null. This flexibility is demonstrated as we assign it a string, such as "21 Brook Street", and later change it to null if necessary. Dart's nullable variables provide flexibility, enabling you to explicitly indicate when a variable might lack a meaningful value.

Data Types

In modern programming languages, unstructured data can pose a significant risk, potentially resulting in errors and code that is challenging to maintain. Consequently, a contemporary programming language must encompass a diverse range of data types to address these challenges effectively.

Data types serve the purpose of specifying the nature of data that a variable can hold and the operations that can be performed on that data. Dart, similar to numerous other programming languages, employs data types to categorize and structure different values, enhancing type safety and enabling the detection of errors during the compilation process. In the upcoming sections, we'll go through some built-in data types in Dart.

Strings

The String data type represents text or character sequences. Dart strings can hold Unicode characters along with integers, letters, and special characters.

Dart provides support for single-line and multi-line strings. You can create a single-line string by enclosing the text within either single quotes (') or double quotes (").

String address1 = '21 Brook Street'; //Single-line string using single quotes
String address2 = "103 Bakers Street"; //Single-line string using double quotes

You can generate multi-line strings using triple quotes (single or double). This feature proves useful for declaring strings that span multiple lines.

String multiLineAddress = """
  23 Dawn Avenue
  Apartment 3B
"""; // Multi-line string using triple double quotes

Numbers

Dart offers various numeric data types to represent different types of numbers, including integers and floating-point numbers. The numeric data types in Dart are listed below:

  • num (Number): The num data type is essential for handling both integers and floating-point numbers in Dart. You can explicitly declare a variable with the num data type like this:

      num userId = 33; // Explicitly declaring a num variable that holds an integer value
      num userNum = 2.1823 // // Explicitly declaring a num variable that holds a floating-point value
    
  • int (Integer): The int data type, representing integer numbers, encompasses both positive and negative values and is an extension of the num data type. You can explicitly declare an integer variable with the int data type, as demonstrated below:

      int userId = 42; // Explicitly declaring an int variable
    
  • double (Floating-Point): The double data type is used to handle floating-point or real numbers, which encompass numbers with fractional components. The double data type also extends the num data type, and you can explicitly declare a double-precision floating-point variable with the double data type, as shown in this example:

      double userNum = 2.8214; // Explicitly declaring a double variable
    

Booleans

In Dart, the keyword bool represents the boolean data type, where values indicate binary states or yes/no conditions. Dart has two well-known literal values:

  • true

  • false.

The true value signifies a condition that is considered positive, correct, or valid, while the false value indicates a condition that is negative, incorrect, or invalid.

In Dart, you declare a boolean variable using the bool keyword followed by the variable name.

bool isProgrammingFun = true;
bool isProgrammingEasy = false;

In the example above, we declare and initialize two boolean variables, isProgrammingFun with true and isProgrammingEasy with false, This code establishes two boolean variables capable of representing binary conditions in a Dart program.

List

A list consists of values that can be of various data types or the same type, and it maintains the order of the elements as they are listed. To create a list in Dart, you can utilize two types of list literals: List and List<T>, where T signifies the type of elements you intend to store in the list.

List dynamicList = [1, "two", 3.0, true];
List<int> numbersList = [1, 2, 3, 4, 5];

In the example above, dynamicList is a list capable of holding elements of different types, while numbersList is a list specifically typed to contain only integers.

Indexes facilitate the access of items within a list. The list's first element is at index 0, the second element at index 1, and so forth.

For instance, with the list of integers below:

List<int> numbers = [10, 20, 30, 40, 50];
int firstNumber = numbers[0];
int secondNumber = numbers[1];

You can access the elements by their respective indices, such as firstNumber to obtain the value at index 0, which is 10, and secondNumber for the value at index 1, which is 20.

Maps

A map is analogous to a collection of key-value pairs, much like how a car's features are associated with their respective descriptions. Maps excel at storing and retrieving data in an associative manner. In Dart maps, keys are unique, and each key corresponds to a specific value. Both keys and values within a Dart map can represent various data types.

To illustrate, let's consider a map representing a car's features using map literals:

Map<String, String> carFeatures = {
  'Model': 'Sedan',
  'Color': 'Blue',
  'Make': 'Toyota',
};

In this scenario, carFeatures is a map with keys (e.g., 'Model', 'Color') of type String and values (e.g., 'Sedan', 'Blue') also of type String. To access or modify the descriptions linked to specific car features, you can utilize the square bracket notation, as demonstrated below:

String carModel = carFeatures['Model']; // Retrieves the car's model ('Sedan')

In this example, carModel captures the description associated with the 'Model' key, which is 'Sedan.'

Sets

In Dart, a Set represents a collection of distinct elements, where each element can exist only once. Sets lack a specific order for their elements, making them unordered. A critical characteristic of sets is their prohibition of duplicates. Should you attempt to add a duplicate element, the set retains just a single instance of that item. Sets prove particularly valuable for tasks such as eliminating duplicate entries from a list.

To declare a set in Dart, you can utilize curly braces {} and insert elements separated by commas. For example:

Set<int> numberSet = {1, 2, 3, 4, 5};

This line of code establishes a set of integers and promptly populates it with the numbers 1, 2, 3, 4, and 5.

Here's a code example that demonstrates how to utilize a Set to eliminate duplicate entries from a list in Dart:

List<int> numbers = [1, 2, 2, 3, 4, 4, 5, 5, 5];
Set<int> uniqueNumbers = Set<int>.from(numbers);

print(numbers); // prints [1, 2, 2, 3, 4, 4, 5, 5, 5]
print(uniqueNumbers); // prints {1, 2, 3, 4, 5}

In this code, we initiate with a list of numbers that includes duplicate values. We then employ a Set, uniqueNumbers, to filter out the duplicates. The uniqueNumbers Set exclusively preserves the distinct elements, ensuring that duplicates are removed. Upon executing this code, you will observe both the original list and the list with duplicates eliminated.

Enums

Dart employs enums (short for "enumeration") to establish named constant values. This proves advantageous in scenarios where you possess a distinct, well-defined set of options or states. In Dart, the creation of an enum entails using the enum keyword, followed by the enum's name and a list of constant values enclosed within curly braces. These constant values are separated by commas.

For instance, consider the following code block:

enum Color {
  red,
  green,
  blue,
  yellow,
}

In this illustration, the enum is denoted as Color, and it defines four constant values: red, green, blue, and yellow. The Color enum exclusively encompasses these specified constant values.

Conclusion

Understanding Dart variables and data types represents a pivotal milestone in your journey towards mastering the language. Variables, accompanied by their data types, form the bedrock of your code, enabling you to efficiently manipulate various types of data. Whether you're working with text, managing numeric values, or structuring data collections, Dart's variable and data type system equips you with the flexibility and security essential for constructing dependable applications.

As you delve deeper into Dart, it's important to recognize that proficiency in variables and data types merely scratches the surface. The language offers even more features and capabilities, making it a powerful tool for developing web and mobile applications. With this knowledge at your disposal, you're well on your way to achieving expertise as a Dart programmer. Embrace the journey and enjoy your coding endeavors!