Skip to main content

Start Dart programming

Dart is created by Google, and its primary purpose is to leverage C-based languages like C++, C#, and Java. It is a general-purpose programming language that is fast in compile-time, concise, and easy to learn. Dart is purely object-oriented, optionally typed, a class-based language that has excellent support for functional as well as reactive programming.

I am going to divide this Dart programming series into 2 blogs so that it would be easy to digest. This is the first blog from the Dart series in which we are going to discuss basic concepts of Dart language.  In the upcoming blog, I am planning to cover Class, Exception Handling, future, async, and await which are some advanced concepts.

Why Dart?

Flutter is the mobile development framework also developed by Google which uses Dart as its programming language and its very fast for prototyping. I really believe it is the future of cross-platform development as we can develop web, mobile and even server-side applications using Dart.

Basic Syntax

Here is the simple Hello World program in a dart programming language.

Variables and Data Types

Variables are simply a block of memory in our system for which we give our custom name to access it and then we can change the value as needed. Moreover, there is another term we need to know called datatype. Data types are simply a type of data. Data types in dart are objects, therefore their initial value is by default null
Let’s create some variables and learn how to use them. Dart has special support for the following data types:
  • Number (includes int and double)
  • Strings
  • Boolean
  • List
  • Maps
  • Runes (for expressing Unicode character in String)
  • Symbols
Let’s define the above syntax:
  • //This is a comment A single-line comment which is useful for notes to programmers. 
  • 10 A number literal. Shubham Hupare A string literal for which both quotes are supported in dart. '...' or "..."
  • int Integer data types can store all those integer number values which are numbers without decimal points.
  • var A way to declare a variable without specifying its type.
  • main() This is the top-level function where our application execution starts and it is required.
  • bool Boolean is a special data type that contains only two values i.e true and false.
  • ; A semicolon is the termination of every statement.
  • var age = 10; We are evaluating what is on the right (10) side of the equals sign and assigning that value to what’s on the left-hand side of the equal sign.
  • $variable OR ${expression} String interpolation: This meaning including a variable or expression’s string equivalent inside a string literal. An expression is simply a combination of one or more variables, operators, and functions that computes to produce another value.
  • 'What\'s’ This is called an escape character. When we have to write a single quote inside a string literal with a single quote, we use it as \ .

  • Dart does has operator precedence, i.e some operators are treated as more important than others. For example, * is used first then + operator. Similar to Mathematics. We can make sure some operator evaluate first than others using parentheses. (100 — 20)*2 .
  • x += 10 This simply means whatever the value of the score, add 10 to it i.e x = x + 10; This operation is so frequent that there is a shortcut way of doing it, i.e += . Similarly, we have +=, -=, *=, /= .
  • x++ If we want to add 1 to a value we can simplify it by x++ or x += 1 instead of writing the full statement.

Conditional Code

Till now, we have been writing simple one-line code. All the code we have written executes from top to bottom. What if we want them to execute if certain conditions are met. In programming, we may have to take decisions based on some calculation. For example, if the player’s current score is greater than a high score, show “You have achieved a high score”. That's called Conditional Programming.

if(condition1){...} else if(condition2) {...} else {...} These means do the first block of code if condition1 is true, the second block if condition2 is true and if both are not true then do the last block of code.
  • condition ? exp1 : exp2 If the condition is true, evaluate exp1 and return its value, otherwise, evaluate and returns the value of exp2 .
  • exp1 ?? exp2 If exp1 is non-null, returns its value; otherwise, evaluates and returns the value of exp2.
Sometimes there may a specific situation where it’s not the only option for checking a condition maybe we’re checking a variable for a specific value. We can do it using if else condition but will become long pretty soon. In that case, switch case is the better option.

Control Statement

We can also hear people call this Loops or Iterations. All our loops have conditions that control how long we need to loop and when to stop.

  • do{ ...} while(condition); Do..While loop will always run its block first while the while(condition){ ... } loop evaluates first before running.
  • break; Break jumps out of the loop and stops executing that loop. While continue; continues the loop.
  • for(initialization; condition; increment){..} It has starting value, a range or condition and increment or decrement. We can also use forEach for collections (discussed later)

Modular Code

After writing statements and conditional code, our code starts to become long and dirty, and harder to understand. So, we break them apart into smaller chunks called functions or methods in dart. These make our code easy to understand and also reusable. A function is simply a chunk of code which we then wrap up using braces and then call them whenever we want. To define them, functions are a collection of statements grouped together to perform an operation. All functions in Dart return a value. If no return value is specified the function return null. Specifying return type is optional but is recommended as per code convention.

  • int findPerimeter() This is a function definition that returns int. If the function returns nothing we should write void as a return type. If we have to call this function we simply write the function name with parentheses which means calling that function. findPerimeter(); .
  • Use fat arrow for single line functions and remove return keyword and { }. Just One Expression function.
  • Anonymous functions are functions that are dynamically declared at runtime. They’re called anonymous functions because they aren’t given a name in the same way as normal functions. If the function is only used once, or a limited number of times, it may be syntactically lighter than using a named function. Like we are printing all people using an anonymous function.
  • There are two types of parameters in Dart: Required parameters and Optional Parameters. Under optional parameter, there are another three types called optional positional parameters, optional named parameters and optional default parameters. Named parameter prevents errors if there are a large number of parameters.

Collections

A collection is an idea of storing values just like variables but it can store multiple values and all those values are contained in one named variable. It is a great way of keeping data together that belong together. In Dart, List and Sets are part of the core library so we don’t have to import those. For others, we need to import from another package. Importing concept will be explained later.

  • Enum: Enums are simply a list of constants. When we need a predefined list of values we use enums. In dart, we cannot put enum inside the main function. It is the simplest of the collection.
  • List: List is an indexable collection of values with a length. The list has a zero-based index. There are two types of list, Fixed length and Growable list. List<int> numbers = new List<int>(); Creating a variable type of generic of int (List that only has int).
  • Set: Set can store certain values, without any particular order, and no repeated values.
  • Queue: Queue can store ordered, has no index, and add and remove operation can be done from the start and end. It is not a part of the standard collection so we need to import it. import 'dart:collection'; .
  • Map: Map can store key/value pairs. They are composed of a collection of (key, value) pairs, such that each possible key appears at most once in the collection. They can add items and we do not need to know their index and just need to know keys which can be any datatype (esp. String and int).

This is it for this blog. Hope you got an idea of syntax, variables, functions, and collections in the Dart programming language. In the upcoming blog, I am planning to cover Class, Exception Handling, future, async, and await which are some advanced concepts. Thank you for reading this blog!!


Comments

Popular posts from this blog

Positive side of "Work From Home"

"Right state of mind is an extremely important trigger to support, sustain and scale up remote work or WFH." In this COVID-19 pandemic situation, companies all over the world allow their employees to work from home. Initially many employers were facing problems while giving employees access to all the tools they’d need to work from home. But after everyone settled in, what quickly became apparent to many office-based teams is that employees could be productive and focused when not in the office—in many cases, even more so. Employers everywhere began to understand that remote work really works. As this WFH is a part of our life now, I thought to start a series of WFH related blogs that might be helpful to other employees as well as the candidate who is going to be a part of corporate life. In this blog, I am going to tell you the positive side of working from home that I observed over the last 1.5 years. 1. Better Work-Life balance A lot of work that can be done remotely nowad...

What is Non-fungible token (NFT)?

Recently, Facebook CEO Mark Zuckerberg rebranded the social giant as Meta Platforms Inc., underscoring the growing popularity of a promising phenomenon: the metaverse. This Metaverse concept has a connection with non-fungible tokens (NFTs), the very token we can use to represent ownership of unique items? Hence in this blog, we are going to understand first what is NFT and then in further blogs I am planning to cover Metaverse. What is an NFT? The acronym NFT means non-fungible token, which means a unique digital asset that cannot be modified or replaced with something else on the blockchain. Unlike Bitcoin, which is a fungible cryptocurrency, which can be traded for a predetermined value, like any other currency or money. An NFT is a unique token with no interchangeability with other tokens – much more like a piece of art. Those unique NFTs do not have a set standardized value. Instead, non-fungible tokens (again much like art) are based on the current market value. The ...

Google I/O 2023 key highlights (Generative AI, New Pixel devices and more)

“AI is having a very busy year,” said Google CEO Sundar Pichai, kickstarting Google I/O 2023 at the Shoreline Amphitheatre. He said, the ‘AI company is reimagining all core products, including search with Generative AI, alongside announcing groundbreaking developments that will reshape the way users interact with the company’s suite of products and services. Gmail with "Help me write" feature After features like Smart Reply and Smart Compose, Gmail is now getting a new feature called “help me write.” It is a simple feature that can help you save time and effort when composing emails. Say your flight was just canceled and you want to write an email asking for a refund. The new feature can grab flight details from the airline cancelation email and compose a draft email for you. If you think it is too small, there is an option to “Elaborate” to make it more compelling, or you can even click on “Recreate” for a completely new email. The feature will start rolling out as a part o...