learning dart

consider fireship course (install freeship userscript)

Dart is very similar to TS/JS

int? a;
a ??= 3; // a = 3
web.document.querySelector('#confirm')
  ?..textContent = 'Confirm'
  ..classList.add('important')
  ..onClick.listen((e) => web.window.alert('Confirmed!'))
  ..scrollIntoView();
  // these are all methods in `button`
  // can also be used to set property values of an object

function params

int sumUpToFive(int a, [int b = 2, int c = 3, int d = 4, int e = 5]) {}
the parameters wrapped in [] are optional, their default value is null unless a default value is provided. they are always last in a function's param list.

there is also named parameters that are wrapped in {}.
when you call a fn with named params you must specify the name of the param and pass the value fn(name='andres')

variables

inheritance

mixin Piloted {
  int astronauts = 1;

  void describeCrew() {
    print('Number of astronauts: $astronauts');
  }
}

---
class PilotedCraft extends Spacecraft with Piloted {
  // PilotedCraft now has attrs and method of both
}

enums

enums are kinda weird and seem to be defined or behave sorta like a class.

Asynchronous programming

http.get('https://example.com').then((response) {
  if (response.statusCode == 200) {
    print('Success!');
  }  
}
// http.get() immediately returns a Future that holds on to the callback until the request resolves.

This same model is how Stream works. Stream provide values in the future and repeatedly over time.

Stream<int> sumStream(Stream<int> stream) async* {
  var sum = 0;
  await for (final value in stream) {
    yield sum += value;
  }
}

concurrency programming

a common solution for concurrency are shared-memory threads but shared state concurrency is error prone and can lead to complicated code.

isolates can share communicate with message passing, but none of the state in an isolate is accessible by others.

if the UI becomes unresponsive due to a large time-consuming computation, consider offloading it to a worker isolate (background worker).

since isolates use separate mem, if you have a global mutable var on the main isolate and mutate it on a spawned isolate, the original var will remain untouched.

isolates are not supported on Web. can use web workers there instead which are similar but differ from isolates.