Beginning Programming with Dart

In these scenarios, the control statement comes into play.

We can also hear people call it Loops or Iterations.

All our loops have conditions that control how long we need to loop and when to stop.

/// Do loopint value;int init = 1;int max = 5;value = init;do { print value; value++;} while (value < max);// 1 2 3 4// While Loopwhile(value <= max){ print value; value++;}// 1 2 3 4 5// Infinite Loopdo { print('Value'); value++; if(value == 3){ print('value is 3'); continue; // Continue the loop } if(value > 5){ print('value is greater than 5'); break; // jumps out of the loop }} while(true);// For EachList people = ['Sharad', 'Ram', 'Hari'];// Starting value, range, incrementfor(int i = 0; i < people.

length; i++){ print("Person at ${i} is ${person[i]}");}people.

forEach((String person) { print(person);});do{ .

} while(condition);Do 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.

Whilecontinue; continues the loop.

for(initilization; condition; incremnet){.

} It has starting value, a range or condition and increment or decrement.

We can also use forEach for collections (discussed later).

Modular CodeAfter 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 returns a value.

If no return value is specified the function return null.

Specifying return type is optional but is recommended as per code convention.

void main(){ print(findArea(4, 5)); findPerimeter(4,5);}int findPerimeter(int length, int breadth){ // Required Parameter return length + breadth;}void findArea(int length, int breadth){ print(length * breadth);}findArea(int length, int breadth){ // By default, if no return value is specified, function returns null}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(); .

void main(){ int rectArea = getArea(10, 5); findPerimeter(4, 2);}void findPerimeter(int l, int b) => print("Perimeter: ${2*(l+b)}");int getArea(int l, int b) => l * b;// Anonymous Functions (internal functions)() { print('Hello'); } // Nothing happens because its not invokedList people = [ 'Sharad', 'Ghimire']; // We will cover List later people.

forEach(print); people.

forEach(() { print(name);});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.

void main(){ printCities("Dang", "Tulsipur", "Ghorahi"); // Must have all 3 arg printCountries("Nepal", "India"); // Will get null in s3 print(findVolume(2, h: 10, b: 3)); // Sequence does not matter var result = findArea(length: 2);}// Required Parametersvoid printCities(String s1, String s2, String s3) => print("First: ${s1}, Second: ${s2}, Third: ${s3}");//Optional Parameters [parameter]void printCounties(String s1, String s2, [String s3]) => print("First: ${s1}, Second: ${s2}, Third: ${s3}");// Optional Named Parameterint findVolume(int l, {int b, int h}) => l * b * h;// Optional Default Parameterint findArea({int length, int breadth = 10}) => length * breadth;CollectionsA 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.

For example, names of countries, or breed of dogs, and so on.

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.

import 'dart:collection';//enumenum colors { red, green , blue } main(List<String> arguments) { print(colors.

values); // [colors.

red, colors.

green, colors.

blue] print(colors.

red); List test = [1, 2, 3, 4]; // Fixed length list print(test.

length); print(test[0]); // Gives item at index 0 print(test.

elementAt(2)); //3 // Growable List of generic type List things = new List(); things.

add(1); things.

add('cats'); things.

add(true); List<int> numbers = new List<int>(); //new creates a new object in memory numbers.

add(1); Set<int> numbers = new Set<int>(); numbers.

add(1); numbers.

add(2); numbers.

add(1); print(numbers); // [1, 2] Queue items = new Queue(); items.

add(1); items.

add(3); items.

add(2); items.

removeFirst(); items.

removeLast(); print(items); // { 3 } Map people = { 'firstname': 'Sharad', 'lastname': 'Ghimire' }; print(people.

keys); // (firstname, lastname) print(people.

values); // (Sharad, Ghimire) print(people['firstname']); // Sharad Map<String, String> people = new Map<String, String>(); people.

putIfAbsent('firstname', () => 'Sharad'); }Enum: Enums are simply a list of constants.

When we need a predefined list of values we use enums.

For example, Names of days, or months, etc.

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).

Note: List is the most basic and most used collection so we will heavily use it.

Other collections are an advanced topic which will be further discussed in Data Structure 101 article.

Let's Handle that ErrorWhen we get beyond all the above basic construct of programming, it’s certain that our code breaks.

So, we write a few lines of code, we then check it and fix it and again write some.

This loop is crucial for every programmer out there.

There is some construct provided by dart that can help us track those errors and solve them.

Error Handling is an advanced topic but we will cover some basics here.

// Error is a program failure// Exception are errors that can be handledint age;int dogyears = 7;print(age * dogyears); //Unhandled exception: NoSuchMethodError: The method '*' was called on null.

// Try Catch Finallytry { int age; int dogyears = 7; print(age * dogyears);}on NoSuchMethodError { // Catch specific error print('Sorry thats not gonna happen');}catch(e) { print("There was an error: ${e.

toString()}");}finally { // Clean up print("Compete");}// Throwing Exceptiontry { int age; int dogyears = 7; if(dogyears != 7) throw new Exception('Dog years must be 7'); // Custom exception if(age == null) throw new NullThrowError(); print(age * dogyears);}on NullThrownError{ print("The value was null!!");}on NoSuchMethodError { print('Sorry no such method!');}catch(e) { print("There was an error: ${e.

toString()}");}finally { print("Complete");}A common usage of try, catch and finally together is to obtain and use resources from database in a try block, deal with exceptional circumstances in a catch block like network failure or not available, and release the resources in the finally block like close that database.

We can also catch a specific exception by using on keyword.

ConclusionYou are now a beginner programmer in Dart Language.

This is just the first part of the 3 part series.

In the second part, we will go deeper into Classes and Generics and also File Systems.

And finally, in the last advanced part, we will discuss Asynchronous Programming, Functional Programming, Reactive Programming and Database Programming and much more.

For now, have a good weekend.


. More details

Leave a Reply