Irbisa · Cheatsheet

Dart Basics

Variables, types, functions, null safety, and core Dart syntax

Junior Developer · 22 questions

  1. 01

    What are the built-in types in Dart, and what does "everything is an object" mean?

    Dart's core types are int and double (both subtypes of num), String, bool, and the collections List, Set and Map.

  2. 02

    What is the difference between var, dynamic and Object? in Dart?

    var asks the compiler to infer a static type from the initializer; dynamic switches static type checking off; Object? is a real type that accepts any value but lets you call almost nothing until you check what it is.

    void main() {  var name = 'Alice';        // inferred as String  // name = 42;              // compile error   dynamic value = 'Alice';  value = 42;                // allowed: no static type…
  3. 03

    What is the difference between final and const in Dart?

    Both mean the variable is assigned once.

    final startedAt = DateTime.now();   // runtime value: fine for final// const now = DateTime.now();      // compile error: not a constant const maxItems = 100;const colors = ['red', 'green'];    // deeply immutable…
  4. 04

    What is sound null safety in Dart, and how do nullable and non-nullable types differ?

    A type without ? can never hold null, and the compiler enforces it; String? explicitly allows null.

    void show(String? email) {      // may be null  // print(email.length);       // compile error: email may be null  if (email != null) {    print(email.length);        // promoted to String inside the if  }}…
  5. 05

    What do the null-aware operators ?., ??, ??=, ?.., ...? and the ! operator do?

    They handle null without writing if statements: ?. accesses a member only when the receiver is not null, ?? supplies a fallback, ??= assigns only when the variable is null, and ! asserts that a value is not null and throws if it is.

    class User {  final String? nickname;  User(this.nickname);} String label(User? user) =>…
  6. 06

    What do is, is! and as do in Dart, and why can as crash at runtime while is cannot?

    is and is! test a value's runtime type and return a bool, and a successful check promotes the variable to that type.

    double priceOf(Map<String, dynamic> json) {  // wrong: throws when the server sends 10 instead of 10.0  // return json['price'] as double;   // right: accept int or double, convert once  return (json['price'] as num).toDouble();…
  7. 07

    What is the difference between positional, named and optional parameters in Dart, and what does required do?

    By default a parameter is positional and required.

    int add(int a, int b) => a + b;  // positional, required // optional positional: in [ ], must come lastString log(String msg, [String level = 'INFO']) => '[$level] $msg'; // named: in { }, any order at the call site…
  8. 08

    What are arrow functions, anonymous functions and closures in Dart?

    In Dart a function is a value: you can store it in a variable, pass it to another function and return it.

    int twice(int x) => x * 2; // named function, arrow body // closure: the returned function keeps `count` aliveint Function() makeCounter() {  var count = 0;  return () => ++count;…
  9. 09

    What is a typedef in Dart, and how do you declare a function type?

    A function type describes a signature: void Function(String) means "takes a String, returns nothing".

    // a function type written inlinevoid run(int Function(int, int) op) => print(op(2, 3)); // the same idea with namestypedef BinaryOp = int Function(int a, int b);typedef Json = Map<String, dynamic>;          // alias for any type…
  10. 10

    What can a Dart enum hold since Dart 2.17 (fields, a const constructor, methods, implements), and how do you turn one into a String and back?

    Since Dart 2.17 an enum is a class with a fixed set of constant instances: it can have final fields, a const constructor, methods and getters, and can implement interfaces.

    enum Plan implements Comparable<Plan> {  free(priceCents: 0, maxProjects: 3),  pro(priceCents: 999, maxProjects: 50),  team(priceCents: 2999, maxProjects: 500);   const Plan({required this.priceCents, required this.maxProjects});…
  11. 11

    What is the difference between List, Set and Map, and which collection methods should every Dart developer know?

    Choose by how you read the data: List keeps order and allows duplicates, Set holds unique values with a fast contains, Map looks values up by a unique key.

    class User {  final int id;  final String name;  const User(this.id, this.name);}…
  12. 12

    How do the cascade .., the spread ... and collection if / for work in Dart?

    The cascade .. performs several operations on the same object and evaluates to that object.

    class Request {  String method = 'GET';  final headers = <String, String>{};  void send() => print('$method $headers');}…
  13. 13

    What does this code print, and how does Dart pass objects to variables and functions?

    void reassign(List<int> items) {  items = [99];} void mutate(List<int> items) {  items.add(4);} void main() {  final a = [1, 2, 3];  final b = a;  b.add(0);  reassign(a);  mutate(b);  print(a);}

    It prints [1, 2, 3, 0, 4].

  14. 14

    If each of lines A–E ran on its own, which would throw at runtime, and what kind of list is each variable?

    void main() {  final a = [1, 2];  a.add(3);                    // line A   const b = [1, 2];  b.add(3);                    // line B   final c = List.unmodifiable(a);  c[0] = 9;                    // line C   final d = List.filled(2, 0);  d[0] = 9;                    // line D  d.add(1);                    // line E}

    Lines B, C and E throw an UnsupportedError; A and D work.

  15. 15

    Find the bug: placing one X on this board puts an X in every row.

    class Board {  Board(this.size) : cells = List.filled(size, List.filled(size, '.'));   final int size;  final List<List<String>> cells;   void place(int row, int col, String mark) => cells[row][col] = mark;   String render() => cells.map((row) => row.join()).join('\n');} void main() {  final board = Board(3)..place(0, 1, 'X');  print(board.render());}

    List.filled evaluates its fill value once, so every row is the same inner list object.

  16. 16

    How does error handling work in Dart, and what is the difference between an Exception and an Error?

    You wrap risky code in try, handle specific types with on Type, get the object and stack trace with catch (e, st), and clean up in finally.

    class PaymentDeclined implements Exception {  final String code;  const PaymentDeclined(this.code);  @override  String toString() => 'PaymentDeclined($code)';}…
  17. 17

    What is assert for in Dart, and why must production validation use throw and debug-only branches use kDebugMode?

    assert(condition, message) checks your own assumptions during development.

    import 'package:flutter/foundation.dart'; class Badge {  final int count;  // our own invariant: checked in debug, gone in release  const Badge(this.count) : assert(count >= 0, 'count must be >= 0');…
  18. 18

    What does this code print, and why do the for loop and the while loop behave differently?

    void main() {  final callbacks = <void Function()>[];   for (var i = 0; i < 3; i++) {    callbacks.add(() => print(i));  }   var j = 0;  while (j < 3) {    callbacks.add(() => print(j));    j++;  }   for (final cb in callbacks) cb();}

    It prints 0 1 2 3 3 3, one number per line.

  19. 19

    Find the bug: this controller sometimes crashes with "Null check operator used on a null value" in refreshAvatar.

    class ProfileController {  ProfileController(this.api);  final AvatarApi api;  User? user; // cleared on logout   Future<void> refreshAvatar() async {    if (user == null) return;    final url = await api.fetchAvatarUrl(user!.id);    user!.avatarUrl = url;  }   void logout() => user = null;}

    user is a field, and the await lets other code run: if logout() sets it to null while the request is in flight, user! on the last line throws.

  20. 20

    What is the difference between == and identical() in Dart, and how does const canonicalization affect it?

    identical(a, b) checks whether two references point to the same object in memory; == checks equality as the class defines it.

    class Point {  final int x, y;  const Point(this.x, this.y);} class Money {…
  21. 21

    Why is 0.1 + 0.2 == 0.3 false in Dart, and how should you store and calculate money?

    double is a 64-bit binary floating-point number, and values like 0.1 have no exact binary form, so small rounding errors appear and add up.

    String formatCents(int cents) =>    '${cents ~/ 100}.${(cents % 100).toString().padLeft(2, '0')}'; void main() {  print(0.1 + 0.2);                         // 0.30000000000000004  print(0.1 + 0.2 == 0.3);                  // false…
  22. 22

    How do UTC and local DateTime values differ in Dart, and how do you store and compare dates so users abroad see the right time?

    A DateTime holds an instant (microseconds since 1970 UTC) plus an isUtc flag; it stores no time zone.

    void main() {  // wrong: no Z, parsed as LOCAL, so the instant differs per device  final a = DateTime.parse('2026-03-29T10:00:00');  // right: explicit UTC, the same instant everywhere  final b = DateTime.parse('2026-03-29T10:00:00Z');…