Browser to Beyond: A Front-End Developer's Path to Mobile Development

Learning the Fundamentals of Dart

ยท

7 min read

Browser to Beyond: A Front-End Developer's Path to Mobile Development

Introduction

Hello everyone! I'm excited to share my latest discoveries in Dart programming with you. Today, we will touch on some fundamental aspects of Dart, including comments, keywords, and data type. Okay then, let's get Darting.

Comments

Comments in programming languages are used to explain code for better understanding and to make code easier to maintain. Comments are ignored by the compiler.

Types of Comments in Dart

Dart supports three types of comments:

  1. Single Line Comments

  2. Multi Line Comments

  3. Documentation Comments

Single Line Comment

In Dart, a single line comment starts with two forward slashes // and extends to the end of the line.

Here's an example of a single line comment:

void main() {
   // This is a single line comment
   // The below code will display the output "Dart is Fun" to the console
   print("Dart is Fun");
}

In the above code, the single line comments will be ignored by the compiler and only the command print("Dart is Fun") will be executed.

Multi Line Comments

In Dart, a multi line comment starts with a forward slash and an asterisk and ends with an asterisk and a forward slash, like so: /* multi line comment */.

Multi line comments are used for longer explanations or commenting out blocks of code because, unlike single line comments, multi line comments can span across multiple lines.

Here's an example of multi line comments:

void main() {
   /* This code demonstrates the use of multi line comments and also
      calculates and displays the sum of two numbers
   */
   int num1 = 10;
   int num2 = 25;
   print(num1 + num2);
}

Documentation Comments

In Dart, documentation comments start with three forward slashes ///.

Documentation comments in Dart are special comments that help generate automatic documentation for your code. These comments are recognized by Dart's documentation tool, Dartdoc, which uses them to create HTML documentation that developers can refer to. This makes it easier to understand what your code does without having to read through the code itself.

Here's an example of how documentation comments are used in Dart:

/// Calculates the sum of two numbers
/// 
/// Takes [num1] and [num2] as parameters 
int calculateSum(int num1, int num2) {
    return num1 + num2;
}
void main() {
  int result = calculateSum(5, 3);
}

Breakdown of Documentation Comments:

  • ///Calculates the sum of two numbers: This comment describes what the function calculateSum does, which is calculating the sum of two numbers.

  • /// Takes [num1] and [num2] as parameters: This comment explains what the parameters num1 and num2 are used for in the function.

Although comments are not compulsory, they are a best practice in code writing. Comments enhance readability, facilitate maintenance, and provide context, making the code more accessible for others and your future self.

Keywords

Keywords are special words in a programming language that have specific meanings and roles. You can't use them for naming things like variables, functions, or classes because they are already set aside for particular tasks in the language.

Keywords in Dart

For example, in Dart, some keywords are if, else, for, while`, class, abstract, static, return, true, false, await, async, void, import, export, extends, implements, interface, new, super, this, throw, try, catch, finally, enum, break, continue, assert, get, set, operator, typedef, dynamic, final, const, null, bool, int, double, String, List, Map, and so on.

Click here to learn more about Dart keywords

Data Types

Data types are categories of data that tell a programming language what kind of value a variable can hold. They define how the data is stored, processed, and manipulated within a program. For example, a number data type stores numerical values, while a string data type stores sequences of characters.

As we already know, Dart is a statically-typed programming language, which means that variables are declared to have specific data types.

Data types in Dart

Below is a list of some of the data types supported in Dart:

  • Numbers

  • Strings

  • Booleans

  • Lists (array)

  • Maps

  • Sets

  • Records

  • Runes

  • Symbols

  • Enums

  • Dynamic

Let's take a closer look at some of these data types.

Numbers

Numbers represent numeric values. Dart supports two types of numbers: integers (whole numbers like 1, 4, 50, 100) and doubles (decimal numbers like 23.6, 55.7, 3.147, 1.5).

Example of number data types in Dart:

void main() {
  int wholeNumber = 42; // Number type integer
  double decimalNumber = 3.14; // Number type double
  print(wholeNumber); // Output: 42
  print(decimalNumber); // Output: 3.14
}

Note: Once wholeNumber is initialized as an integer int, it cannot be changed to a decimal point number. Attempting to assign a double value to wholeNumber will result in an error. However, decimalNumber can be assigned both integer and decimal values since it is of type double.

Strings

Strings are sequences of characters enclosed in single or double quotes. They are used to represent text.

Example of string data type in Dart:

void main() {
  String greeting = 'Hello, World!';
  String name = "John Abdul";
  print(greeting); // Output: Hello, World!
  print(name); // Output: John Abdul
}

Note: Strings are used to store text and cannot store numbers directly unless enclosed in single or double quotes, i.e., "24".

Booleans

Booleans represent true or false values. They are often used in conditional statements.

Example of boolean data type in Dart:

void main() {
  bool isTrue = true;
  bool isFalse = false;
  print(isTrue); // Output: true
  print(isFalse); // Output: false
}

Note: Booleans can only hold true or false values and cannot be assigned any other type of value.

Lists

Lists are ordered collections of items. Each item can be accessed by its index, starting from zero, similar to an array in JavaScript.

Example of list data types in Dart:

void main() {
  List<int> numbers = [1, 2, 3, 4, 5];
  List<String> words = ['apple', 'banana', 'cherry'];
  List<dynamic> random = ['apple', 'banana', 3, 4, 5, true, false];
  print(numbers); // Output: [1, 2, 3, 4, 5]
  print(words); // Output: [apple, banana, cherry]
   // Accessing items
  print(numbers[0]); // Output: 1
  print(words[1]); // Output: banana
  print(random[5]); // Output: true
}

Note: Lists can store multiple values of the same type and are accessed using an index.

Maps

Maps are collections of key-value pairs. Each key is associated with a value, and you can access a value by its key, kind of like an object in JavaScript.

Example of map data type in Dart:

void main() {
   Map<String, int> ages = {'Abishola': 30,'Bob': 25,'Isah': 35};
   print(ages); // Output: {Abishola: 30, Bob: 25, Isah: 35}
    // Accessing values
   print(ages['Abishola']); // Output: 30
   print(ages['Bob']); // Output: 25
}

Note: Maps allow you to store data in key-value pairs, where each key is unique.

Dynamic

Dynamic is a special type that indicates that the variable can hold any type of data. The type of the variable can change during runtime.

Unlike in JavaScript where you can do this:

var name = "John";
name = 200;

and get away with it, in Dart you will be met with an error saying since you've already initialized the variable name to be equal to a string "John" in line one, you can't come to line two and expect to reassign it to a value with a different data type like 200 or true.

To be able to change a variable from one data type to another conveniently in Dart, you will have to use the dynamic data type.

Example of dynamic data types in Dart:

void main() {
   dynamic random = 42;
   print(random); // Output: 42
   random = 'A string now';
   print(random); // Output: A string now
   random = true;
   print(random); // Output: true
}

Note: Dynamic variables can hold any type of value, and the type can change during runtime. This provides flexibility but should be used with caution as it can lead to runtime errors.

That's all I can cover about data types for now. From what I know, the ones explained above are the most commonly used data types in Dart, but there's more to explore. To learn more about data types in Dart, click here

Conclusion

In this article, we explored the basics of comments, keywords, and data types in Dart. Comments help in making the code more readable and maintainable, while keywords are reserved words with special meanings in the language. Data types define the kind of values that variables can hold, ensuring type safety and consistency in your code.

Understanding these fundamental concepts is crucial for writing efficient and error-free Dart programs. For further learning, you can refer to the official Dart documentation.

Thanks for reading! If you found this article helpful, please share it with others and leave your thoughts in the comments below.

Bye for now! But Remember, "In Dart, as in life, semicolons are not optional." ๐Ÿ˜ŠHappy coding!๐Ÿ˜Š

ย