Programming with Erik

815 Followers
·

The Dart Programming Language in Five Minutes

A quick overview for those already familiar with similar languages, like Java, Kotlin, C++, and C#

Image for post
Image for post
Photo by Silvan Arnet on Unsplash

Dart is primarily known as the programming language for Flutter, Google’s UI toolkit for building natively compiled mobile, web, and desktop apps from a single codebase. It’s optimized for building user-interfaces and developed by Google. It’s used to build mobile, desktop, server, and web applications. Dart can compile to native code and JavaScript.

If you want to follow along with this article, which I highly recommend, you can do so without installing anything on DartPad.dev.

Image for post
Image for post
Dartpad.dev allows you to experiment with Dart from the browser —screenshot by author

Hello World

Let’s start with the obligatory “Hello world”:

void main() {
print('Hello World!');
}

A few conclusions that can already be drawn:

  • Dart needs a main() function as a starting point
  • Dart doesn’t require a class (Like C, unlike Java)
  • Dart uses two-character indentation by convention

Two character indentation makes the code more compact. This is really helpful when you start creating a Flutter application since Flutter apps are based on a tree of nested widgets, which can get out of soon.

Dart code is compact

class Person {
String name;
int age;

Person(this.name, this.age);

int lieAboutMyAge() {
print("My name is $name, my age is ${age - 10}");
}

}
void main() {
final me = Person("Erik", 38);
var girlfriend = Person("Shannon", 30);

me.lieAboutMyAge();
}

Dart code has many modern features to reduce code size. As you can see from the above example:

  • You can simply refer to instance variables in a bodiless constructor to automatically assign values to them
  • Strings have template-like features, allowing you to directly use variables or even expressions like ${age - 10}
  • When creating objects, you don’t need to use the new keyword, but if you want, you can
  • Dart supports both top-level functions like main() and class methods.

Type Inference

Dart is strongly typed. But did you notice that Dart uses type inference? We didn’t need to specify the type (Person) of the variables me and girlfriend. Instead, Dart inferred the type for us at compile time. This is in line with other modern languages like Kotlin.

Final and Const

If you are sure a variable won’t change, you can declare it final. If you’re not sure — perhaps you’ll find another girlfriend next week — you use var.

There’s also a const modifier, which is a bit more difficult to grasp and has effect on the value.

A final variable can be assigned after compile time, like storing the response of an HTTP request, while a const must be known and defined before compilation.

If a collection or object is a const, it’s complete state is immutable at compile-time, hence it must be created from data that is available at compile time. In contrast, if a variable is final, you can’t reassign a new object to it, but you can still change the collection or object that it points to.

Objects

Everything that can be assigned to a variable, is an object. Even numbers, functions, and null are objects. All objects are based on a class, and all objects inherit from a base object with the unsurprising name Object.

I like languages that do this because it allows numbers to have convenience methods like isNegative and isOdd , resulting in pleasant code that almost reads like a good novel:

if (age.isNegative) {
print("The age can not be negative, you fool!")
}

Speaking about numbers, Dart make life easier by only offering two types of numbers: integers and doubles (both 64 bits and signed).

Private and public

All identifiers are public by default. Dart doesn’t have keywords for public, private, or protected.

A library in Dart is everything that is in a single file. So library privacy means that the identifier is visible only inside the file that the identifier is defined in. To mark a Dart identifier private to its library, start its name with an underscore.

Expressions and statements

Dart has both expressions that result in a value and statements like if… else that don’t. This doesn’t differ from most other languages. Some of the usual suspects that are available in Dart too:

  • while loops and for loops
  • if…else statements
  • The switch statement
  • The construct condition ? [expression if true] : [expression if false]
  • Exceptions

Lists, Sets, and Maps

Dart supports these data types natively. Let’s look at some examples to get a feel for these data types, starting with lists:

var myList = [1, 2, 3];
assert(myList.length == 3);
assert(myList[1] == 2);
var constantList = const [1, 2, 3];
constantList[1] = 1; // This causes an error!

Sets are unordered collections of unique items:

var mySet = {'john', 'eric', 'martha'};
var elements = <String>{};
elements.add('fluorine');

Something that will bite you sometime: if you forget the type annotation on a set definition like the above one for elements, a map will be created. This is simply because maps also use accolades, and maps appeared first in the Dart language.

A map associates keys and values that can be any type. The following map is inferred to the type Map<String, String>:

var gifts = {
'first': 'partridge',
'second': 'turtledoves',
'fifth': 'golden rings'
};
gifts['fourth'] = 'calling birds';

Dart Package Manager

The website https://pub.dev/ contains publicly available packages that can be installed easily with Dart’s package manager, pub. The website, as of writing this, contains more than twelve thousand packages, some for Dart and many specifically for Flutter.

You can also use pub to install locally downloaded packages or packages hosted on GitHub.

Conclusion

Dart is a modern, easy to learn language. If you want to dive in deeper, I recommend one or more of the following sites:

Written by

Software developer by day, writer at night.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store