Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 73 ยท Dart essentials

More Dart: Comments, Numbers, Input, Enums and Accessors

Fill the gaps in your Dart: doc comments, stdin and stdout, BigInt and runes, num methods, bitwise operators, Queue, enums, switch and labels, getters and setters, exit.

The earlier Dart lessons cover what you meet in almost every Flutter file. This lesson collects the smaller pieces of the language that show up sooner or later: the three kinds of comments, reading input in a command-line program, big integers and Unicode, the many helpers on numbers, bitwise operators, the Queue collection, how enums really work, switch statements with labels, getters and setters, and how a program ends.

Dart cannot run on this site, so every Dart block is read-only. Where a behavior is easy to imitate, a JavaScript TryIt shows the same idea. Those stand-ins are JavaScript, and we point out where the two languages differ.

Comments

Dart has three comment styles:

DART
// A single-line comment runs to the end of the line.

/* A multi-line comment
   can span several lines. */

/// A documentation comment. It is written in Markdown and attached
/// to the declaration that follows it. Use [Account] to link to a name.
class Account {
  /// The current balance in cents.
  int balance = 0;
}

Documentation comments start with /// (the older /** ... */ form also works, but /// is the recommended style). Tools such as the dart doc command and your editor's hover tooltips read them, so write them for every public class and method. Plain // comments are for explaining tricky code to other developers, and a line like // TODO: handle errors is picked up by editors as a reminder.

Reading input and writing output

Flutter apps get input from widgets, but plain Dart programs (scripts, tools, servers) use the dart:io library. stdout.write prints without a trailing newline, and stdin.readLineSync() reads one line:

DART
import 'dart:io';

void main() {
  stdout.write('Your name: ');
  final String? name = stdin.readLineSync();   // null at end of input
  stdout.write('Your age: ');
  final age = int.tryParse(stdin.readLineSync() ?? '') ?? 0;
  print('Hello, ${name ?? 'stranger'}! Next year you will be ${age + 1}.');
}

readLineSync() returns String?, because the input can end. Always handle the null, as above. dart:io does not exist on the web, and there is no console in a phone app, so in Flutter you read text with a TextField instead (see Forms and Validation).

main() and exiting

Every Dart program starts at main(). It can optionally receive the command-line arguments:

DART
import 'dart:io';

void main(List<String> args) {
  if (args.isEmpty) {
    stderr.writeln('Usage: tool <file>');
    exit(64);          // stop right here with exit code 64
  }
  print('Reading ${args.first}');
}

exit(code) from dart:io ends the program at once; code 0 means success and anything else means failure. Do not call it in a Flutter app: it kills the app without cleanup, and iOS rejects apps that close themselves. On Android you can call SystemNavigator.pop() from package:flutter/services.dart to leave the current screen or app in the standard way.

Numbers in depth

int and double share the superclass num, so a variable of type num can hold either one. On the Dart VM (phones and desktop) an int is a 64-bit signed integer. When Dart is compiled to JavaScript for the web, numbers are JavaScript numbers, so integers are only exact up to 2^53.

DART
print(7 / 2);          // 3.5   (/ always gives a double)
print(7 ~/ 2);         // 3     (integer division, truncates)
print(-7 ~/ 2);        // -3
print(-7 % 3);         // 2     (% is never negative when the divisor is positive)
print((-7).remainder(3)); // -1  (remainder keeps the sign of the dividend)

print((-2.5).round());    // -3   (halves round away from zero)
print((-2.5).floor());    // -3
print((-2.5).ceil());     // -2
print((-2.5).truncate()); // -2
print(3.14159.toStringAsFixed(2)); // 3.14

print((-4).isNegative);          // true
print((1 / 0).isInfinite);       // true
print((0 / 0).isNaN);            // true
print(int.parse('42') + 1);      // 43
print(int.tryParse('4x2'));      // null: no exception
print(5.toDouble());             // 5.0
print(5.9.toInt());              // 5

The difference between % and remainder surprises people who come from JavaScript, Java or C, where % behaves like Dart's remainder. Use % for things like wrapping an index around a list, because the result is always a valid index.

This TryIt imitates those operations in JavaScript so that you can try other values:

JS Dart number rules, imitated in JavaScript

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The output shows 2, -1, -3, -3, then -2 for JavaScript's own Math.round (which is why we needed a helper), -3 -2 -2 and 3.14.

Bitwise operators

Dart has the usual bitwise operators for integers: & (and), | (or), ^ (xor), ~ (not), << and >> (shifts), and >>> (unsigned right shift, added in Dart 2.14):

DART
print(5 & 3);    // 1    (101 & 011 = 001)
print(5 | 3);    // 7    (101 | 011 = 111)
print(5 ^ 3);    // 6    (101 ^ 011 = 110)
print(~5);       // -6
print(1 << 4);   // 16
print(-16 >> 2); // -4   (the sign is kept)
print(16 >>> 2); // 4

Bit flags and masks are the usual reason to use them, for example checking a permission bit with (flags & 4) != 0.

BigInt

When 64 bits are not enough, BigInt from the core library holds integers of any size. It does not mix with int in arithmetic, so convert explicitly:

DART
final big = BigInt.parse('123456789012345678901234567890');
print(big * BigInt.two);              // 246913578024691357802469135780
print(BigInt.from(2).pow(100));       // 1267650600228229401496703205376
print(big.toString().length);         // 30
// print(big + 1);                    // error: 1 is an int, not a BigInt
print(big + BigInt.one);

Runes and Unicode

A Dart String is a sequence of UTF-16 code units. Most characters take one unit, but emoji and many rare symbols take two, so length can be larger than what a person sees. A rune is a full Unicode code point:

DART
final s = 'a\u{1F600}b';          // a, a grinning face, b
print(s.length);                   // 4  (the emoji takes two code units)
print(s.runes.length);             // 3
print(s.runes.toList());           // [97, 128512, 98]
print(String.fromCharCodes([72, 105]));  // Hi
print(String.fromCharCode(0x1F600));

Runes still split some visible characters (a flag or a family emoji is several code points). For text that users type, the characters package, which every Flutter project already has, counts what a person sees: the flag of Norway has two code points but .characters.length is 1.

This TryIt shows the same units-versus-code-points difference in JavaScript, together with its own big integers:

JS Code points and big integers in JavaScript

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Queue

A List is slow at removing from the front because every element moves. Queue from dart:collection is a double-ended queue: adding and removing at both ends is fast.

DART
import 'dart:collection';

void main() {
  final q = Queue<int>();
  q.addLast(2);
  q.addLast(3);
  q.addFirst(1);
  print(q);               // {1, 2, 3}
  print(q.removeFirst()); // 1
  print(q.removeLast());  // 3
  print(q.first);         // 2
  print(q.length);        // 1
}

Use a queue for breadth-first searches, task lines and "last N items" buffers. A queue allows duplicates, so it is not a Set.

Enums, switch and labels

An enum declares a fixed set of values. Each value knows its position and its name:

DART
enum Level { low, medium, high }

void main() {
  print(Level.medium.index);           // 1
  print(Level.medium.name);            // medium
  print(Level.values);                 // [Level.low, Level.medium, Level.high]
  print(Level.values.byName('high'));  // Level.high
}

Enums have limits, and knowing them saves time. You cannot create extra instances yourself, extend an enum, or add values at run time. All instance fields must be final and the constructor must be const. An enum value is not a number, so there is no automatic conversion to int; use .index, or add a field as shown in Dart Classes.

Switch details

A switch over an enum should list every case, and Dart checks this for you:

DART
String describe(Level level) {
  switch (level) {
    case Level.low:
      return 'relax';
    case Level.medium:
    case Level.high:          // an empty case falls into the next one
      return 'pay attention';
  }
}

A non-empty case ends by itself, so you do not write break and cannot fall through by accident. An empty case is the one exception, shown above; in Dart 3 you can also write case Level.medium || Level.high:. A switch can sit inside another switch, but a nested decision is often clearer as a separate function.

Labels

Dart has no goto, but you can label a loop and then break or continue that specific loop from inside an inner loop:

DART
void main() {
  final grid = [[1, 2, 3], [4, -5, 6], [7, 8, 9]];

  outer:
  for (var r = 0; r < grid.length; r++) {
    for (var c = 0; c < grid[r].length; c++) {
      if (grid[r][c] < 0) {
        print('negative at $r,$c');
        break outer;          // leaves both loops
      }
    }
  }
}

continue outer; skips to the next iteration of the labeled loop. JavaScript has the same syntax, so you can run the idea here:

JS break and continue with labels (JavaScript)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The output is first negative at [ 1, 1 ], rows that contain an even number: 3, 1,2,3 and 1 3 2. A JavaScript shift() can be slow on huge arrays, while Dart's Queue removes from the front in constant time.

Getters and setters

Getters and setters let a class expose a value that looks like a field but runs code. A getter has no parameter list; a setter takes exactly one parameter:

DART
class Temperature {
  double _celsius;                        // private: starts with _

  Temperature(this._celsius);

  double get celsius => _celsius;         // getter

  set celsius(double value) {             // setter with validation
    if (value < -273.15) {
      throw ArgumentError('below absolute zero');
    }
    _celsius = value;
  }

  double get fahrenheit => _celsius * 9 / 5 + 32;  // computed, read-only
}

void main() {
  final t = Temperature(20);
  print(t.fahrenheit);   // 68.0
  t.celsius = 100;
  print(t.fahrenheit);   // 212.0
  // t.fahrenheit = 0;   // compile error: no setter
}

Callers write t.celsius = 100 exactly as they would for a plain field, so you can start with a public field and add validation later without changing any calling code. That is why Dart style says: do not write trivial getters and setters for every field. Privacy in Dart is per library (usually per file), not per class, so _celsius is hidden from other files but visible to the rest of this one.

Here is the same class in JavaScript, where the private field syntax is #:

JS Getters and setters (JavaScript stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The difference: in Dart, assigning to a getter-only property is a compile error, while in JavaScript it fails only when the code runs (in a module, as here).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does -7 % 3 evaluate to in Dart?

    Dart's % operator returns a non-negative result for a positive divisor, so -7 % 3 is 2. The remainder() method gives -1.
  2. 2. Which comment style is used for documentation that tools can read?

    Documentation comments start with ///. They are written in Markdown and used by dart doc and editor tooltips.
  3. 3. Why does 'a๐Ÿ˜€b'.length differ from the number of runes?

    A String is a sequence of UTF-16 code units. The emoji needs two of them, while runes count full Unicode code points.
  4. 4. What does stdin.readLineSync() return when the input has ended?

    Its type is String?, so you must handle null, for example with ?? ''.
  5. 5. How do you leave two nested loops at once in Dart?

    Dart has no goto, but a labeled outer loop can be left from the inner loop with break label;.

Summary

  • Use // for notes and /// (Markdown) for documentation that tools show.
  • stdin.readLineSync() returns String?; dart:io is for command-line programs, not Flutter widgets. exit() ends a program, but never use it in a Flutter app.
  • % is never negative for a positive divisor, remainder follows the dividend's sign, ~/ truncates, and round rounds halves away from zero.
  • BigInt holds integers of any size; runes are full Unicode code points, and characters counts what users see.
  • Queue from dart:collection adds and removes fast at both ends.
  • Enums have index, name and values, but cannot be extended or instantiated; a switch over an enum should cover every value, and labels let you break or continue an outer loop.
  • Getters and setters look like fields to callers, so validation can be added later.

Next: Futures, async/await and Streams