पाठ 3 / 25

Dart Essentials for Flutter

Null safety, final and const, async and classes.

The Dart you use every day

Dart 3 is soundly null safe: String can never be null, String? can, and you handle nullable values with ?., ?? or a null check. var infers a type, final is assigned once at runtime, and const is a compile-time constant (Flutter uses const widgets heavily). Asynchronous work returns a Future<T> and is written with async/await; repeated events use a Stream<T>. Classes support named parameters marked required, initialiser shorthand (this.name) and factory constructors. Dart 3 also added records such as (int, String) and patterns with switch expressions for destructuring.

Dart in one screen

Null safety, a class, async and a switch expression.

class User {
  final String name;
  final String? nickname; // may be null
  const User({required this.name, this.nickname});

  String get display => nickname ?? name;
}

Future<User> loadUser() async {
  await Future.delayed(const Duration(milliseconds: 300));
  return const User(name: 'Asha');
}

(int, String) parse(String raw) => (raw.length, raw.trim()); // a record

String label(int count) => switch (count) {
      0 => 'none',
      1 => 'one',
      _ => 'many',
    };

Future<void> main() async {
  final user = await loadUser();
  final (len, text) = parse('  hi '); // destructuring pattern
  print('${user.display} $len $text ${label(len)}');
}

Avoid the bang operator

Writing value! tells Dart "trust me, this is not null" and throws at runtime if you are wrong. Prefer ?? defaults, if (x != null) checks or patterns.

त्वरित जाँच: What is the difference between final and const in Dart?

  • final only works on classes
  • They are identical
  • const variables can be reassigned
  • final is set once at runtime; const must be known at compile time
Answer

final is set once at runtime; const must be known at compile time — const values are canonicalised compile-time constants, which Flutter uses to skip rebuild work.