Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 61 ยท Real-World Dart

From Dart to Flutter and Dart on the Server

See where your Dart skills lead: Flutter widgets and hot reload, calling C with dart:ffi, talking to JavaScript with js_interop, and every compile target.

Dart is a general-purpose language, but most people meet it through Flutter, Google's toolkit for building apps for phones, desktops and the web from one code base. The same language also runs on servers, in command-line tools and in the browser. Once you know Dart itself, the question becomes: how does it connect to everything else?

This lesson is a map, not a full course. You will see how a Flutter app is organized, why hot reload feels magical, how Dart calls native C libraries with dart:ffi, how it talks to JavaScript, and which compile target to pick for which job. Dart and Flutter are not installed on this site, so the Dart snippets are read-only. The TypeScript stand-ins model the ideas (widget trees, state, reload) with code that really runs.

Flutter in one page

A Flutter app is a tree of widgets. A widget is an immutable description of a piece of the screen: "a padded column holding a title and a button". You never move or edit widgets on screen. When something changes, you describe the new screen again, and Flutter works out what actually needs to be redrawn.

DART
import 'package:flutter/material.dart';

void main() => runApp(const GreetingApp());

class GreetingApp extends StatelessWidget {
  const GreetingApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Hello')),
        body: const Center(child: Text('Welcome to Flutter')),
      ),
    );
  }
}

Notice how much of this is plain Dart you already know: a const constructor with a named parameter, super.key as an initializing formal, an @override method, and an expression-bodied main. Flutter leans on the language features from the earlier chapters: named and required parameters for readable widget constructors, const so unchanged subtrees are never rebuilt, and sealed classes and records for modelling state.

There are two kinds of widgets you write yourself:

  • A StatelessWidget only depends on its constructor arguments. Its build method returns the same thing for the same inputs.
  • A StatefulWidget owns mutable data in a separate State object. When the data changes you call setState, which tells Flutter to call build again.
DART
class Counter extends StatefulWidget {
  const Counter({super.key});

  @override
  State<Counter> createState() => _CounterState();
}

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

  @override
  Widget build(BuildContext context) {
    return TextButton(
      onPressed: () => setState(() => _count++),
      child: Text('Pressed $_count times'),
    );
  }
}

The widget class is recreated freely and is cheap. The State object lives on, which is why _count survives rebuilds. The underscore keeps _CounterState private to its library, exactly as in getters and setters.

flowchart TD
    A["runApp(GreetingApp)"] --> B["MaterialApp"]
    B --> C["Scaffold"]
    C --> D["AppBar"]
    C --> E["Center"]
    D --> F["Text: Hello"]
    E --> G["Text: Welcome to Flutter"]

A widget tree. Each box is an immutable description; Flutter compares old and new trees and updates only what changed.

The first stand-in shows the core idea. Widgets are small immutable objects, and build expands them until only primitive elements are left, which are then drawn (here, printed as indented text).

TypeScript A widget tree and its build method (stand-in)

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Hot reload and why Dart makes it possible

When you run a Flutter app in development, you can edit the source, press save, and see the change in under a second without losing where you were in the app. That is hot reload.

It works because debug builds run on the Dart virtual machine with a JIT compiler (see what is Dart). The tooling sends the changed code to the running VM, which swaps in the new method bodies. Then Flutter rebuilds the widget tree. Existing objects, including your State objects, stay alive, so a counter keeps its value.

Some changes cannot be applied that way, for example changing what a field initializer does after the object already exists, or editing main. For those you use hot restart, which starts the program again with fresh state (still much faster than a full rebuild). Release builds do not use the JIT at all: they are compiled ahead of time to native code, which is why a shipped app starts fast and has no VM warm-up.

TypeScript Hot reload keeps state, hot restart resets it (stand-in)

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Calling C with dart:ffi

Sometimes the code you need already exists as a C library: image codecs, encryption, a database engine. The foreign function interface in dart:ffi lets a Dart program that runs natively (not on the web) call it directly, with no plugin layer in between.

You describe the C signature once with native types (Int32, Double, Pointer<Utf8>) and once with the Dart types you want to call it with:

DART
import 'dart:ffi';

typedef NativeAbs = Int32 Function(Int32);
typedef DartAbs = int Function(int);

void main() {
  // On Linux and macOS the C standard library is already loaded in the process.
  final lib = DynamicLibrary.process();
  final abs = lib.lookupFunction<NativeAbs, DartAbs>('abs');
  print(abs(-42)); // 42
}

DynamicLibrary.open('libfoo.so') loads a specific library file, and lookupFunction finds a symbol by name and wraps it in a Dart function. Newer Dart versions also offer an @Native annotation on external functions, which removes the lookup code. Strings and structs need manual memory management with Pointer, malloc and free (from package:ffi), so wrap every FFI call in a small, well-tested Dart function and keep raw pointers out of the rest of your code. Because C has no safety net, a wrong signature crashes the program instead of throwing an exception.

Talking to JavaScript

When Dart is compiled for the browser, it needs to call browser APIs and JavaScript libraries. Modern Dart does this with dart:js_interop and the package:web bindings. You declare JavaScript names with @JS and external, and use extension types (from extension methods) as zero-cost wrappers around JavaScript objects.

DART
import 'dart:js_interop';
import 'package:web/web.dart';

@JS('Math.max')
external double jsMax(double a, double b);

void main() {
  final heading = document.createElement('h1');
  heading.textContent = 'Hello from Dart';
  document.body!.append(heading);

  print(jsMax(3, 9)); // 9.0
}

Values cross the boundary as JS types (JSString, JSNumber, JSArray, JSFunction), and the conversion getters .toJS and .toDart move between the two worlds. Older tutorials mention dart:html and package:js; they are deprecated in favour of the approach above, so prefer it for new code.

Choosing a compile target

One Dart code base can become several kinds of output. The dart compile command (and Flutter's build tooling) pick the target:

Target Command Good for
Run from source (JIT) dart run Development, scripts, fast edit-run cycle
Native executable (AOT) dart compile exe CLI tools and servers that start quickly with no SDK installed
AOT snapshot dart compile aot-snapshot Smaller files run with the dartaot runtime
JavaScript dart compile js Web apps for every browser
WebAssembly dart compile wasm Web apps on browsers with WasmGC support
flowchart LR
    S["Dart source"] --> J["JIT VM<br/>dart run, hot reload"]
    S --> A["AOT native code<br/>exe, mobile, desktop"]
    S --> W["JavaScript or Wasm<br/>browser"]

One language, three families of output.

Dart on the server

A server is just a long-running command-line program. Compile it with dart compile exe bin/server.dart -o server, copy the single file into a small container, and run it. The shelf package gives you request handlers and middleware, and frameworks such as Dart Frog and Serverpod add routing and code generation on top. The big advantage is shared code: a Flutter app and its backend can use the same model classes, validation and JSON conversion, as you saw in JSON and serialization.

Treat Flutter as a library you add on later. Everything in this tutorial (null safety, collections, classes, futures and streams) is exactly what Flutter code uses, so the time you spent on the language transfers fully.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does a Flutter State object keep its values across rebuilds?

    Widgets are cheap, immutable descriptions that are rebuilt freely. The separate State object persists, so fields such as a counter survive.
  2. 2. What makes hot reload possible during development?

    The VM can swap in changed method bodies while the program runs. Release builds are compiled ahead of time and cannot do this.
  3. 3. Which tool lets a native Dart program call a function in a C library?

    dart:ffi describes C signatures and wraps C functions as Dart functions. js_interop is for JavaScript, shelf is for HTTP servers.
  4. 4. Which command produces a self-contained native executable for a server?

    dart compile exe builds an ahead-of-time compiled executable that needs no Dart SDK on the target machine.

Summary

  • Flutter apps are trees of immutable widgets; StatelessWidget depends only on inputs, StatefulWidget keeps data in a State object and calls setState to rebuild.
  • Hot reload works because debug builds run on the JIT-enabled Dart VM; release builds are AOT-compiled native code.
  • dart:ffi calls C libraries from native Dart programs; wrap raw pointers in small, tested functions.
  • dart:js_interop with @JS, external and extension types connects web-targeted Dart to JavaScript.
  • dart compile offers exe, aot-snapshot, js and wasm; servers are ordinary compiled Dart programs that can share model code with a Flutter app.

Next: common Dart mistakes and pitfalls.