Dart for Web Developers

For a full intro into the language, checkout Dart for Web Developers

Sections

About Dart

Dart is an application programming language that’s easy to learn, easy to scale, and deployable everywhere. Google depends on Dart to make very large apps.-dartlang.org

The first hurdle to most would-be Flutter developers is being convinced tolearn a new, sparsely used Language: Dart.

If you're coming from a C-like syntax language like Java, it'll be very easyto learn. If you're coming from JavaScrtipt, there are some important differences.

I imagine a lot of Flutter developers are going to be coming from the world ofJavaScript, so I'll point out the major differences between JS and Dart here.

'Dart is an object-oriented, class defined, single inheritance language using a C-style syntax that transcompiles optionally into JavaScript. It supports interfaces, mixins, abstract classes, reified generics, optional typing, and a sound type system'.-Wikipedia

Syntactically, you're in good shape if you've ever used TypeScript or Java. In fact, for JS web developers, the biggest road block to overcome is going be using a typed language. You'll also potentially have to get used to Object Oriented Programming, as JavaScript uses a prototypical hierarchy that's fairly unique.

The 'main' function

When Dart is ready to run, it looks for a main function to execute. Every Dart program must start with the main function.

  1. void main() {
  2. // ... execute program
  3. }

Printing to the console

To log anything to the console, use the built in function 'print':

  1. void main() {
  2. print('Logging to the console: ... ');
  3. }
  4. // -> Logging to the console: ...

Dart Type System

This is the biggest difference.

JavaScript doesn't support any kind of types. Dart (as of Dart 2), is a strongly typed language, and Types are not optional.

  1. // JavaScript
  2. var one = 1
  3. var name = 'Rick'
  1. // Dart
  2. int one = 1;
  3. String name = 'Rick';

A strong type system makes you more productive. The tooling is better, and your compiler catches many more errors much easier.

Dart does support a var keyword, which means it can be anything.

  1. //Dart
  2. // Okay
  3. var name = 'Rick';

When writing functions in Dart, you start by declaring the type that it willreturn:

  1. // Dart
  2. // void means it returns nothing
  3. void main () {
  4. print('hello world');
  5. }
  6. // this function returns an int
  7. // and the argument it accepts is an int
  8. int multiplyByTwo (int number) {
  9. return number * 2;
  10. }

When writing data-structures like Lists and Maps, you can add types with thefollowing syntax:

  1. List<String> names = ['Aaron', 'Ahmed', 'Alex'];
  2. Map<String, String> userInfo = {'firstName': 'Kevin', 'lastName': 'Durant'};

Default Values

(I'm sorry about the soapbox…)

The most insane thing about JavaScript is that literally anything goes. Not enough arguments passed to a function? It's fine. Too many arguments? Just ignore the extras. Passing a string into a function that adds numbers? Okay. Everything without a value is undefined, and the compiler is fine to try to push forward anyway.

Dart is not this way. In Dart, everything that doesn't have a value is null, and if you try to execute code that involves a null value, it'll complain.

  1. var name // undefined
  1. // Dart
  2. var name; // null
  3. List x; // null
  4. MyCustomClass variable; // null

In JS, many values are treated as true. Most values, actually. Which is veryconfusing. Also in JS, many values are treated as false. The point is, youcan use many values to 'null check'

  1. // JavaScript
  2. var nullVar = null
  3. if (nullVar) {
  4. // do something
  5. }

In Dart, true is true. False is false. Fullstop. You can't use _anything_other than values that evaluate to booleans in if/else statements:

  1. // Dart
  2. var nullVar;
  3. if (nullVar) {
  4. // throws error, value must evaluate to boolean
  5. };
  6. if (nullVar == null) {
  7. // works
  8. };

Asynchronous Dart

Async programming in Dart has two main aspects: Futures and Streams.

Futures are the same as JS's Promises. A future represents a value that willeventually evaluate.

  1. //Dart
  2. // Return a Future, which will return a null eventually
  3. Future<Null> getApiData() {
  4. final url = 'https://httpbin.org/ip';
  5. HttpRequest.request(url).then((value) {
  6. print(json.decode(value.responseText)['origin']);
  7. }).catchError((error) => print(error));
  8. }

But you can make your life even easier by using async/await, which is exactlylke async/await in other languages, including the new feature in JavaScript.

  1. // Dart
  2. Future<Null> _getIPAddress() async {
  3. final url = 'https://httpbin.org/ip';
  4. var request = await HttpRequest.request(url);
  5. String ip = json.decode(request.responseText)['origin'];
  6. print(ip);
  7. }

Streams

Basically, a stream is an object with tells you when there is new dataavailable. For example, you could establish a stream that listens for newmessages from a database in a chat app.

NB: There is a lot more to it, but you only need to know enough to getstarted.

  1. List<String> messagesToRender = [];
  2. // A Stream Controller will alert all streams when new information is available.
  3. StreamController<List<String>> messagesStream = new StreamController.broadcast();
  4. // A stream itself is what you will listen to.
  5. Stream<List> get onNewMessage => messageStream.stream;
  6. // A listener is what logic you want to execute when a stream updates.
  7. void _subscribeToMessages() {
  8. onNewMessage.listen((data) {
  9. messagesToRender = data;
  10. });
  11. }

For a full intro into the language, checkout Dart for Web Developers