Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

The Programming Shortcut: Dart

Part of The Programming Shortcut, a series that teaches one programming idea per article to people who already program. This one is about UI as a function of state.

A language for drawing screens

Dart is a general-purpose language. You can write a command-line tool in it, or a server. But almost nobody comes to Dart for that. People come to Dart because of Flutter, Google’s toolkit for building apps that run on phones, desktops and the web from one codebase. Dart is the language Flutter is written in and the language you write Flutter apps in, and it has grown up around that job.

So here is the reframing: Dart is a language for drawing screens.

That sounds narrow, but drawing screens is where most programmers first meet a problem their first language never posed: the screen has to keep matching the program, while the program keeps changing, and while some of the things it’s waiting for haven’t arrived yet. Flutter’s answer to that problem is one of the most useful ideas in modern programming, and it fits in one line:

The screen is a function of the state.

State is the data your program is holding right now: how many items are in the cart, whether you’re logged in, what the server sent back. The claim is that you never change the screen directly. You change the state, and the screen gets drawn again from it, the way a function’s result gets computed again from its arguments.

This article is about that idea, plus the one thing it needs to survive in the real world: async, Dart’s way of waiting for slow things without making the screen wait with you. By the end you should be able to spot the same idea in React, SwiftUI, Jetpack Compose and whatever comes next.

What you already have

Dart will look familiar. It has curly braces and semicolons, and its classes and functions read like those of Java, C#, Kotlin or TypeScript. Variables, loops, conditionals, functions and lists all work the way you expect, so this article skips them. A few rows differ enough to read side by side:

What you knowluxDart
a structstructa class with final fields
a value that might be missingOption<int>int?, and the checker makes you deal with the null
an enum whose cases carry dataenum with payloadsa sealed class, one subclass per case
a match that must cover every casematcha switch expression, checked for every case
showing somethingprint("hi")print('hi') for the console, Text('hi') for the screen

Dart checks types before your program runs, every branch, the way lux and TypeScript do. (The introduction’s typo demo shows what that means.) The last row, Text for the screen, is where this article slows down.

Save, press r

You need one tool: Flutter, which brings Dart with it. Follow the install guide for your system, then run this to check that everything is in place:

flutter doctor

Now make an app and start it:

flutter create hello_screen
cd hello_screen
flutter run

flutter create writes a small starter app. flutter run builds it and opens it as a desktop app on your computer (or asks which device to use, if it finds more than one). The app is a counter: a number in the middle and a button that adds one to it.

Press the button a few times, so the counter says 5 or so. Now open lib/main.dart in any editor, find the text 'You have pushed the button this many times:', and change it to something of your own. Save the file. Go back to the terminal where flutter run is still running, and press r.

The text changes in under a second. And the counter still says 5.

That’s hot reload: Flutter swaps your new code into the running app without starting it over. You’ll use it for the rest of this article, and it’s already showing you the main idea. Your code changed, the screen was drawn again, and the state (the 5) survived, because the state and the drawing are two separate things. Hot reload swaps in new code and keeps the old state. Press R (capital) for a hot restart, which throws the state away too, and the counter goes back to 0.

If you work in VS Code with the Flutter extension, you can make it hot reload every time you save, so the only key you press is save.

The screen is a function of the state

Two ways to keep a screen up to date

Picture a shopping cart screen. It shows a label (“Cart: 3”) and a checkout button that only works when the cart has something in it. When the user adds an item, both have to change.

The older way, still common in many toolkits for graphical user interfaces, is imperative: you keep a handle to each thing on the screen, and when something happens you go and change each one by hand. Set the label’s text. Enable the button. Here it is with plain variables standing in for the label and the button:

var items = 0;
var cartLabel = 'Cart is empty';
var checkoutEnabled = false;

void addItem() {
  items++;
  cartLabel = 'Cart: $items';
}

void main() {
  addItem();
  print(cartLabel);
  print('Checkout enabled: $checkoutEnabled');
}
Cart: 1
Checkout enabled: false

Did you spot the bug before you ran it? addItem forgot the button. The label says there’s an item, the button says there isn’t, and the screen is now lying to the user. Every new thing on the screen is one more line every event handler has to remember, and the handlers multiply: add item, remove item, empty the cart, load a saved cart. Somewhere, one of them forgets.

The other way is declarative: you describe what the screen should look like for a given state, and that’s all you write. One function, state in, screen out:

String view(int items) {
  final label = items == 0 ? 'Cart is empty' : 'Cart: $items';
  final checkout = items > 0 ? 'enabled' : 'disabled';
  return '$label | Checkout $checkout';
}

void main() {
  var items = 0;
  print(view(items));
  items++;
  print(view(items));
}
Cart is empty | Checkout disabled
Cart: 1 | Checkout enabled

Now the label and the button can’t disagree, because they’re both computed from the same number every time. There’s nothing to forget. items is the source of truth: the one place the fact lives. Everything on the screen is derived from it.

If you’ve used lux, you already have half of this. A lux program prints its state. A Flutter screen is its state, printed again every time the state changes.

Who calls the function?

If the screen is a function of the state, somebody has to call that function again whenever the state changes. In Flutter, you change the state inside a call to setState, and setState means: “I’ve changed something; draw me again.” Here is that idea with the framework boiled down to a dozen lines of plain Dart:

class CartScreen {
  int items = 0;

  void setState(void Function() change) {
    change();
    print(build());
  }

  String build() => items == 0 ? 'Cart is empty' : 'Cart: $items';
}

void main() {
  final screen = CartScreen();
  print(screen.build());
  screen.setState(() => screen.items++);
  screen.setState(() => screen.items++);
  screen.setState(() => screen.items = 0);
}
Cart is empty
Cart: 1
Cart: 2
Cart is empty

setState takes a function, runs it to make the change, then calls build to redraw. Real Flutter does the same, with two differences. It doesn’t redraw on the spot: it marks the screen as needing a redraw and does it in time for the next frame. And build doesn’t return a string. It returns widgets.

Widgets are descriptions

A widget in Flutter is a small, cheap object that describes a piece of the screen: some text, a button, a column holding other widgets. It isn’t the thing on the screen. It’s a description of what should be there, like a sketch handed to a painter. Widgets can’t be changed once they’re made; when the state changes, you make new ones.

A widget that has no state of its own is a StatelessWidget, and it’s a function of whatever it was given:

class Greeting extends StatelessWidget {
  const Greeting({super.key, required this.name});
  final String name;

  @override
  Widget build(BuildContext context) => Text('Hello, $name!');
}

A widget that holds state comes in two parts: the widget itself, and a State object that keeps the data and builds the description. Here is a cut-down counter in the same shape as the one you ran a moment ago:

class _CounterState extends State<Counter> {
  int _count = 0;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text('Pushed $_count times'),
        FilledButton(
          onPressed: () => setState(() => _count++),
          child: const Text('Push'),
        ),
      ],
    );
  }
}

(The underscore at the start of a name makes it private to the file. That’s a Dart rule, not a Flutter one.)

Read build the way you read view earlier. Given _count, here’s the screen. Nowhere does the code say “find the text and change it.” When the button is pressed, the count changes inside setState, Flutter calls build again, and it gets back a brand-new description.

Then Flutter compares the new description with the previous one and changes only what differs on the real screen. That comparison is why making a whole new description every time isn’t wasteful: you describe everything, and Flutter does the minimum. You get to write code as if you redrew the world from scratch, and the computer gets to do as little as possible.

Give the state a shape

Once the screen is a function of the state, the most useful thing you can do is make the state say which situations are possible. A screen that loads a list from the internet is in one of three situations: still loading, loaded, or failed. You could track that with a few loose variables (isLoading, names, error) and hope they never contradict each other. Or you could say outright that the state is exactly one of three cases.

Dart says that with a sealed class: a family of classes where every member is known in advance. A switch over one must handle every case, and Dart checks that before the program runs. (This idea of an enum whose cases carry data, and a match that must cover them all, has its fullest explanation in the Rust article.)

sealed class Load {}

final class Loading extends Load {}

final class Loaded extends Load {
  Loaded(this.names);
  final List<String> names;
}

final class Failed extends Load {
  Failed(this.why);
  final String why;
}

String view(Load state) => switch (state) {
  Loading() => 'Spinner goes round…',
  Loaded(:final names) => 'Friends: ${names.join(', ')}',
  Failed(:final why) => 'Something went wrong: $why',
};

void main() {
  print(view(Loading()));
  print(view(Loaded(['Ada', 'Grace'])));
  print(view(Failed('no network')));
}
Spinner goes round…
Friends: Ada, Grace
Something went wrong: no network

Loaded(:final names) matches a Loaded and pulls its names field out into a variable of the same name. Now try deleting the Failed line from the switch:

sealed class Load {}

final class Loading extends Load {}

final class Failed extends Load {}

String view(Load state) => switch (state) {
  Loading() => 'Spinner goes round…',
};

void main() {
  print(view(Loading()));
}

Dart refuses to run it. The type Load is not exhaustively matched by the switch cases, it says, since it doesn’t match Failed(). That’s a screen state you never drew, caught before anyone saw a blank page. When your state has a shape, the checker can tell you whether your screen covers it.

One rule that falls out of all this

If build is a function of the state, it should behave like one. Flutter calls it whenever it likes: when the state changes, when the window is resized, when a parent redraws, as often as every frame during an animation. So build should be quick, and it should only describe. Don’t start a download in build, or change the state there, or print a receipt. Do those things in response to events, then change the state, then let build describe the result.

Waiting without freezing

Real state doesn’t arrive all at once. The friends list comes from a server, and the server takes a second. What does the program do during that second?

It mustn’t stop. A Flutter app runs your Dart code on one thread, the same thread that draws the frames. If your code sits and waits for the network, nothing gets drawn: no spinner, no button presses, a window that looks frozen. So Dart doesn’t wait by sitting still. It has an event loop: a queue of small jobs (draw a frame, handle a tap, finish a network request) that the one thread works through one at a time.

Waiting fits into that loop with two pieces. A Future is a value that will exist later: a ticket you hold while the work goes on elsewhere. await says “pause this function here until the ticket is ready, and let the loop run other jobs in the meantime.” A function that uses await is marked async, and it returns a Future itself. That’s a one-line summary of async and await, which work this way in many languages; the JavaScript article is where the series explains them properly.

Watch the loop keep going while one function waits:

import 'dart:async';

Future<String> fetchFriends() async {
  await Future.delayed(const Duration(seconds: 1));
  return 'Ada, Grace';
}

Future<void> main() async {
  final frames = Timer.periodic(
    const Duration(milliseconds: 300),
    (_) => print('  (frame drawn)'),
  );
  print('Asking the server…');
  final friends = await fetchFriends();
  print('Got: $friends');
  frames.cancel();
}
Asking the server…
  (frame drawn)
  (frame drawn)
  (frame drawn)
Got: Ada, Grace

The Timer stands in for Flutter drawing frames. While main is paused at await, the timer’s jobs keep running. Now swap the friendly wait for a stubborn one, a loop that just spins until the second is up:

import 'dart:async';

Future<String> fetchFriends() async {
  final stop = DateTime.now().add(const Duration(seconds: 1));
  while (DateTime.now().isBefore(stop)) {}
  return 'Ada, Grace';
}

Future<void> main() async {
  final frames = Timer.periodic(
    const Duration(milliseconds: 300),
    (_) => print('  (frame drawn)'),
  );
  print('Asking the server…');
  final friends = await fetchFriends();
  print('Got: $friends');
  frames.cancel();
}
Asking the server…
Got: Ada, Grace

Not one frame. The function still says async, but it never let go of the thread, so for a whole second the app would have been a picture of an app. async doesn’t make work happen somewhere else. It only gives the loop a chance to run other jobs at each await.

Async, meet state

Here’s where the two ideas lock together. The screen never waits. The screen only ever shows the current state. So waiting becomes a state of its own:

Future<void> _loadFriends() async {
  setState(() => _state = Loading());
  try {
    final names = await fetchFriends();
    setState(() => _state = Loaded(names));
  } catch (e) {
    setState(() => _state = Failed('$e'));
  }
}

Set the state to “loading,” and the screen draws a spinner. Await the answer while the loop keeps drawing frames. When it arrives, set the state to “loaded” or “failed,” and the screen draws that. A failed request isn’t a crash or a pop-up thrown from somewhere deep in the code. It’s just another case of the state, and build already knows how to draw it, because the switch made sure.

That pattern (event, change the state, await, change the state again) is most of what an app does all day.

What Dart doesn’t check for you

Dart’s checker is strict. It won’t let a null slip into an int, and it won’t let a switch skip a case. So it’s surprising to find that the central promise of this article is one nobody checks.

Nothing makes you call setState. If you change _count directly, Dart compiles it, Flutter runs it, and the screen just doesn’t change, because nobody told Flutter to call build again. No error, no warning. The screen is a function of the state only as long as you keep telling it when the state changed. It’s a convention, and you keep it.

await has a catch of its own. While your function is paused, the user can leave the screen. When the answer arrives a second later, the widget it was meant for is gone, and calling setState on it is an error Flutter reports at runtime: setState() called after dispose(). The fix is one line after every await that’s followed by a setState: if (!mounted) return;, which asks “am I still on screen?” before touching anything. The _loadFriends fragment above is missing it. The project below has it, and one of its tests fails without it.

Beware of state-management debates before you have state. Search for Flutter help and you’ll soon find people arguing about Provider, Riverpod, Bloc, Redux and a dozen more. These are packages for sharing state across many screens, and each has fans who will tell you it’s the only sane choice. Ignore them for now. They’re all answers to “where should state live when lots of widgets need it?”, and you can’t judge an answer to a question you haven’t had yet. setState and a well shaped state class will carry you a long way. When passing the same data down through five layers of widgets starts to hurt, that’s the time to read Flutter’s own page on the options, and you’ll know what you’re shopping for.

The slow oracle

The project is in projects/dart/. It’s one screen with an oracle on it. You ask a question by pressing a button, the oracle thinks for two seconds, and then it answers. Every fifth time, it gets confused instead.

The oracle’s mood is the state, and it has a shape:

sealed class Mood {}

final class Asleep extends Mood {}

final class Thinking extends Mood {}

final class Spoke extends Mood {
  Spoke(this.answer);
  final String answer;
}

final class Confused extends Mood {
  Confused(this.reason);
  final String reason;
}

Alongside it the screen keeps one number, _asked, the count of questions so far. Everything you see is computed from those two values in build. The headline is a switch over the mood. The spinner appears only while the oracle is Thinking. The button is switched off while it thinks (in Flutter, a button whose onPressed is null is disabled), and its label says “Ask” or “Ask again” depending on _asked. Not one line of the program turns the spinner off, or re-enables the button, or changes the label. When the mood changes, those things follow.

Asking is the async pattern from above, with the mounted check in place:

Future<void> _ask() async {
  setState(() {
    _mood = Thinking();
    _asked++;
  });
  Mood next;
  try {
    next = Spoke(await consult(_asked));
  } catch (e) {
    next = Confused('$e');
  }
  if (!mounted) return;
  setState(() => _mood = next);
}

The project comes with widget tests: small programs that build the screen in memory, tap its button, and check what it shows, with no window at all. (Testing in general has its own article.) Run them from the project folder:

cd projects/dart
flutter test
00:00 +0: the screen follows the oracle through a question
00:00 +1: a failed consultation becomes a state too
00:00 +2: leaving while the oracle thinks is safe
00:00 +3: All tests passed!

The tests finish in well under a second, even though the oracle thinks for two. Widget tests run on a pretend clock, and tester.pump(const Duration(seconds: 2)) moves it forward and redraws, so the test can check the screen at each moment of the wait: thinking, then answered. Open test/widget_test.dart and you’ll see the screen-as-function idea from the other side. Each test sets up a state, and then checks only what’s drawn.

To see the oracle in a window, let Flutter add the platform files the project leaves out, then run it:

flutter create .
flutter run

flutter create . fills in what’s missing and leaves the existing code and tests alone. Ask a few questions. Then change the words Questions asked: in build, save, and press r. The new words appear, and the count stays put.

The end of lib/main.dart has more to try, including what happens when you delete the mounted check, or forget a setState.

What this article skips

This article didn’t cover layout (rows, columns, padding and how Flutter decides sizes), styling and themes, moving between screens, animation, talking to the network for real, or reaching the phone’s camera and sensors. It skipped Stream, Dart’s type for a value that keeps arriving, like messages in a chat. It skipped isolates, Dart’s way of doing heavy work on another thread, which is the real answer to the spinning loop above. And it skipped nearly all of Dart itself.

When you want more, the people who make Dart and Flutter have written it well. The Dart language tour covers the language, and Asynchronous programming covers Future and await in depth. For Flutter, start with the learning pathway, and read Start thinking declaratively, Flutter’s own short page on the idea this article is about.

Read the starter app

Go back to the hello_screen app you made at the start, open lib/main.dart, and read the comments. Flutter’s starter app is full of notes and “TRY THIS” prompts, written by the people who made the framework. One of them explains, in a few lines, what would go wrong if you changed the counter without calling setState.

Bring a question with you: in that file, which lines are the state, and which are the function?

  • JavaScript, for async and await and code that waits for events.
  • Rust, for enums that carry data and matches that cover every case.
  • Testing, for code that checks your code.

Tested with Dart 3.14 and Flutter 3.50.1, November 2026.