Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Dart Documentation

The language behind Flutter — one codebase for Android, iOS, web and desktop apps.

Dart is a modern, object-oriented language from Google, optimised for building user interfaces. It is the language of Flutter, which builds Android, iOS, web and desktop apps from one codebase. Dart has sound null safety, async/await, a fast development cycle (hot reload) and compiles to native machine code or JavaScript.

1. Introduction & Installation

  • Install Flutter from flutter.dev — it includes Dart. Or install only the Dart SDK.
  • Editors: VS Code (Dart + Flutter extensions) or Android Studio.
  • Try code online at dartpad.dev.
dart --version
dart create hello          # new console project
dart run                   # run it
dart run bin/hello.dart    # run a specific file
dart compile exe bin/hello.dart
void main() {
  print('Hello, Codify!');
}

Output:

Hello, Codify!

⚠️ Common error: 'dart' is not recognized — add flutter/bin (or dart-sdk/bin) to your PATH and restart the terminal.

2. Basic Syntax

  • Execution starts at main(). Statements end with ;, blocks use { }.
  • String interpolation: 'Hi $name' and '${expression}'.
  • Comments: //, /* */ and /// documentation comments.
void main() {
  var name = 'Asha';
  var score = 90;
  score += 5;
  print('$name scored $score');
  print('Next level at ${score + 10} points');
  print('Name has ${name.length} letters');
}

Output:

Asha scored 95
Next level at 105 points
Name has 4 letters

⚠️ Common error: a missing semicolon gives Expected ';' after this. — Dart requires them.

3. Variables & Data Types

Keyword / type Meaning
var type inferred, can be reassigned
final set once at runtime
const compile-time constant
int, double, num numbers
String, bool text, true/false
List, Set, Map collections
dynamic turns off type checking (avoid)
Type? nullable — may be null
void main() {
  int count = 10;
  double price = 99.5;
  String city = 'Pune';
  bool active = true;
  final joined = DateTime(2026, 1, 10);
  const maxUsers = 100;
  String? nickname;                       // null by default

  print('$count $price $city $active ${joined.year} $maxUsers');
  print(nickname ?? 'no nickname');       // null-coalescing
  print(nickname?.length);                 // null-aware access
  print(int.parse('42') + 1);
  print(7 / 2);
  print(7 ~/ 2);
  print(3.99.toInt());
  print(10.toString() + '!');
}

Output:

10 99.5 Pune true 2026 100
no nickname
null
43
3.5
3
3
10!

⚠️ Common error: A value of type 'Null' can't be assigned to a variable of type 'String' — non-nullable types can't hold null. Use String? or give a value.

4. Operators

Arithmetic + - * / ~/ % (~/ = integer division), comparison == != < > <= >=, logical && || !, null-aware ?? ??= ?. and ! (assert non-null), type tests is, is!, cast as, the cascade .. and spread ....

void main() {
  print('${17 ~/ 5} ${17 % 5} ${17 / 5}');
  print(5 > 3 && 2 > 1);
  int? stock;
  stock ??= 10;                       // assign only if null
  print(stock);
  Object value = 'text';
  if (value is String) print(value.toUpperCase());   // smart cast
  final list = [1, 2]..add(3)..add(4);               // cascade
  print([0, ...list, 5]);
}

Output:

3 2 3.4
true
10
TEXT
[0, 1, 2, 3, 4, 5]

5. Conditional Statements

String grade(int marks) {
  if (marks >= 90) {
    return 'A';
  } else if (marks >= 75) {
    return 'B';
  }
  return 'C';
}

void main() {
  print(grade(82));

  var day = 'sat';
  switch (day) {
    case 'sat' || 'sun':                  // Dart 3 patterns
      print('Weekend');
    default:
      print('Weekday');
  }

  var temp = 31;
  var feel = switch (temp) {              // switch expression
    > 35 => 'hot',
    > 25 => 'warm',
    _ => 'cool',
  };
  print(feel);
  print(temp > 30 ? 'fan on' : 'fan off');
}

Output:

B
Weekend
warm
fan on

⚠️ Common error: a switch expression must be exhaustive — add a _ => default case.

6. Loops

void main() {
  for (var i = 1; i <= 5; i++) {
    print(i);
    if (i == 2) break;
  }

  var langs = ['dart', 'kotlin', 'swift'];
  for (final lang in langs) {
    print(lang.toUpperCase());
  }

  langs.asMap().forEach((i, l) => print('$i: $l'));

  var n = 1;
  while (n < 100) {
    n *= 3;
  }
  print('n = $n');

  var squares = [for (var i = 1; i <= 4; i++) if (i.isEven) i * i];   // collection-for
  print(squares);
}

Output:

1
2
DART
KOTLIN
SWIFT
0: dart
1: kotlin
2: swift
n = 243
[4, 16]

7. Functions

int add(int a, int b) => a + b;                          // arrow function

String greet(String name, [String greeting = 'Hello']) => // optional positional
    '$greeting, $name!';

String createUser({required String name, int age = 18}) => // named parameters
    '$name ($age)';

int applyTwice(int x, int Function(int) f) => f(f(x));   // function as parameter

Function counter() {
  var c = 0;
  return () => ++c;                                       // closure
}

void main() {
  print(add(2, 3));
  print(greet('Asha'));
  print(greet('Ravi', 'Namaste'));
  print(createUser(name: 'Neha'));
  print(createUser(age: 25, name: 'Kabir'));
  print(applyTwice(3, (n) => n * n));
  final next = counter();
  next();
  print(next());
}

Output:

5
Hello, Asha!
Namaste, Ravi!
Neha (18)
Kabir (25)
81
2

⚠️ Common error: The named parameter 'name' is required, but there's no corresponding argument — pass every required named argument.

8. Collections

void main() {
  var nums = [5, 3, 8, 1, 9];
  nums.add(4);
  nums.sort();
  print(nums);
  print(nums.where((n) => n.isOdd).toList());
  print(nums.map((n) => n * 2).toList());
  print(nums.reduce((a, b) => a + b));
  print(nums.any((n) => n > 8));
  print(nums.first);
  print(nums.last);
  print(nums.sublist(1, 3));

  var ages = {'asha': 21, 'ravi': 23};          // Map
  ages['neha'] = 22;
  ages.update('asha', (a) => a + 1);
  print(ages);
  print(ages['john'] ?? 0);
  print(ages.keys.toList());
  print(ages.containsKey('ravi'));

  var tags = {'dart', 'flutter', 'dart'};       // Set
  print(tags);
  print(tags.length);

  var words = 'to be or not to be'.split(' ');
  var freq = <String, int>{};
  for (final w in words) {
    freq[w] = (freq[w] ?? 0) + 1;
  }
  print(freq);
}

Output:

[1, 3, 4, 5, 8, 9]
[1, 3, 5, 9]
[2, 6, 8, 10, 16, 18]
30
true
1
9
[3, 4]
{asha: 22, ravi: 23, neha: 22}
0
[asha, ravi, neha]
true
{dart, flutter}
2
{to: 2, be: 2, or: 1, not: 1}

⚠️ Common error: .map() and .where() return lazy Iterables — call .toList() when you need a List.

9. Object-Oriented Programming

abstract class Shape {
  double area();
  String get name => 'shape';
}

class Rect extends Shape {
  final double w, h;
  Rect(this.w, this.h);                      // initialising formal parameters
  @override
  double area() => w * h;
  @override
  String get name => 'rect';
}

class Circle extends Shape {
  final double r;
  Circle(this.r);
  @override
  double area() => 3.14159 * r * r;
}

mixin Loggable {                              // reusable behaviour
  void log(String msg) => print('[${runtimeType}] $msg');
}

class Account with Loggable {
  final String owner;
  double _balance;                            // _ = private to the library
  Account(this.owner, [this._balance = 0]);
  Account.empty(String owner) : this(owner); // named constructor

  double get balance => _balance;
  void deposit(double amount) {
    if (amount <= 0) throw ArgumentError('Amount must be positive');
    _balance += amount;
    log('deposited $amount');
  }
}

void main() {
  final shapes = <Shape>[Rect(3, 4), Circle(1)];
  for (final s in shapes) {
    print('${s.name} ${s.area().toStringAsFixed(2)}');
  }
  final acc = Account.empty('Asha');
  acc.deposit(500);
  print('${acc.owner} ${acc.balance}');
}

Output:

rect 12.00
shape 3.14
[Account] deposited 500.0
Asha 500.0

Also: implements (use a class as an interface), factory constructors, static members, enums with fields, sealed classes (Dart 3) and records like (int, String).

10. Advanced Concepts

Async / await and Futures:

Future<String> fetchUser(int id) async {
  await Future.delayed(Duration(milliseconds: 100));   // e.g. an HTTP call
  if (id <= 0) throw Exception('invalid id');
  return 'user$id';
}

Future<void> main() async {
  final user = await fetchUser(1);
  print(user);
  final both = await Future.wait([fetchUser(2), fetchUser(3)]);   // in parallel
  print(both);
  try {
    await fetchUser(0);
  } catch (e) {
    print('Error: $e');
  }
}
user1
[user2, user3]
Error: Exception: invalid id

Streams deliver a sequence of async events:

Stream<int> countdown(int from) async* {
  for (var i = from; i > 0; i--) {
    await Future.delayed(Duration(milliseconds: 10));
    yield i;
  }
}

Future<void> main() async {
  await for (final n in countdown(3)) {
    print(n);
  }
  print('liftoff');
}
3
2
1
liftoff

Records and patterns (Dart 3):

(int, int) minMax(List<int> v) => (v.reduce((a, b) => a < b ? a : b), v.reduce((a, b) => a > b ? a : b));

void main() {
  final (lo, hi) = minMax([4, -2, 9]);
  print('$lo $hi');
  final json = {'name': 'Asha', 'age': 21};
  if (json case {'name': String name, 'age': int age}) {
    print('$name is $age');
  }
}
-2 9
Asha is 21

Flutter basics — everything is a widget:

import 'package:flutter/material.dart';

void main() => runApp(const MaterialApp(home: CounterPage()));

class CounterPage extends StatefulWidget {
  const CounterPage({super.key});
  @override
  State<CounterPage> createState() => _CounterPageState();
}

class _CounterPageState extends State<CounterPage> {
  int count = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Codify Counter')),
      body: Center(child: Text('Tapped $count times', style: const TextStyle(fontSize: 24))),
      floatingActionButton: FloatingActionButton(
        onPressed: () => setState(() => count++),
        child: const Icon(Icons.add),
      ),
    );
  }
}

Key Flutter ideas: StatelessWidget vs StatefulWidget, setState, layout widgets (Column, Row, Stack, ListView), navigation (Navigator.push), packages from pub.dev (http, provider, riverpod, go_router), and hot reload (r in the terminal).

11. Examples with Output

Example 1 — Palindrome check

bool isPalindrome(String s) {
  final clean = s.toLowerCase().replaceAll(RegExp(r'[^a-z0-9]'), '');
  return clean == clean.split('').reversed.join();
}

void main() {
  print(isPalindrome('A man, a plan, a canal: Panama'));
  print(isPalindrome('Dart'));
}
true
false

Example 2 — Two Sum with a Map

List<int> twoSum(List<int> nums, int target) {
  final seen = <int, int>{};
  for (var i = 0; i < nums.length; i++) {
    final need = target - nums[i];
    if (seen.containsKey(need)) return [seen[need]!, i];
    seen[nums[i]] = i;
  }
  return [];
}

void main() => print(twoSum([2, 7, 11, 15], 9));
[0, 1]

Example 3 — Group students by grade

void main() {
  final marks = {'Asha': 91, 'Ravi': 78, 'Neha': 85, 'Kabir': 66};
  final byGrade = <String, List<String>>{};
  marks.forEach((name, m) {
    final g = m >= 85 ? 'A' : m >= 70 ? 'B' : 'C';
    byGrade.putIfAbsent(g, () => []).add(name);
  });
  print(byGrade);
}
{A: [Asha, Neha], B: [Ravi], C: [Kabir]}

12. Practice Problems

  1. Read a line with stdin.readLineSync() (from dart:io) and print it reversed.
  2. Write isPrime(int n) and list primes below 50.
  3. Build a BankAccount class with deposit/withdraw that throws on insufficient balance.
  4. Use a Map<String, List<int>> to store marks per student and print averages.
  5. Fetch JSON from a public API with the http package and print five titles.
  6. Write a Stream that emits a number every second and stops after 5.
  7. Build a Flutter to-do app: add, delete and mark tasks done.
  8. Solve the logic of Two Sum and Valid Parentheses in Dart (submit in Java/C++/Python on Codify).

13. Interview Questions

1. What is sound null safety? Types are non-nullable by default; String? may be null. The compiler guarantees a non-nullable variable never holds null at runtime.

2. final vs const? final is set once at runtime; const is a compile-time constant (and makes objects canonical and deeply immutable).

3. What are Futures and Streams? A Future is a single value available later; a Stream is a sequence of values over time. Use await for Futures and await for/listen for Streams.

4. What is a mixin? A way to reuse code across class hierarchies (with Loggable) without inheritance.

5. extends vs implements vs with? extends inherits implementation (one parent), implements promises an interface (must implement all members), with mixes in mixins.

6. What is the cascade operator? .. performs several operations on the same object: list..add(1)..add(2).

7. What are isolates? Dart's concurrency model: isolated workers with their own memory that communicate by messages (no shared state).

8. Stateless vs Stateful widgets? Stateless widgets depend only on their inputs; stateful widgets hold mutable State and rebuild via setState.

9. What is hot reload? Injecting changed code into the running Dart VM so the Flutter UI updates in about a second while keeping state.

10. JIT vs AOT in Dart? JIT compilation powers fast development and hot reload; AOT compilation produces fast native release builds.

14. Cheat Sheet & References

Basics

void main() { print('Hi $name ${a + b}'); }
var x = 5; final y = 10; const z = 15; String? maybe;
int.parse('42'); double.parse('2.5'); 42.toString(); 7 ~/ 2;
maybe ?? 'default'; maybe?.length; value!;

Control flow

if (a) {} else if (b) {} else {}
for (var i = 0; i < n; i++) {} for (final x in list) {}
while (cond) {} do {} while (cond);
var r = switch (x) { 1 => 'one', _ => 'other' };

Collections

var l = [1, 2]; l.add(3); l.remove(1); l.length; l.contains(2);
l.where((x) => x > 1).map((x) => x * 2).toList(); l.reduce((a, b) => a + b);
var m = {'a': 1}; m['b'] = 2; m.keys; m.values; m.containsKey('a'); m.forEach((k, v) {});
var s = {1, 2}; s.add(3); [...l, 4]; [for (var x in l) x * 2];

Functions and classes

int add(int a, int b) => a + b;
void f({required String name, int age = 18}) {}
class P { final int x; P(this.x); P.zero() : x = 0; }
class Q extends P with M implements I { Q() : super(1); @override String toString() => 'Q'; }

Async

Future<int> load() async { await Future.delayed(Duration(seconds: 1)); return 1; }
final v = await load(); await Future.wait([a(), b()]);
Stream<int> s() async* { yield 1; } await for (final x in s()) {}
try { await load(); } catch (e) { print(e); } finally {}

Flutter CLI

# create, run, build
flutter create my_app
flutter run
flutter pub add http
flutter build apk

Official documentation