Flutter Tutorial

Flutter Beginner Lesson 2 of 135 3 min read

Dart for Flutter: The Dart You Need Before Learning Flutter

The Dart every Flutter beginner needs on one page: variables, named parameters, classes, null safety, lists, maps and async await, with runnable examples.

On this page

Flutter apps are written in Dart. You do not need to master Dart first, but you do need the pieces below, because every Flutter widget uses them. Run each example and change it. When something is unclear, the full Dart tutorial explains it step by step.

Variables and types

void main() {
  var name = 'Asha';     // String, worked out by Dart
  int age = 21;
  double price = 9.99;
  bool isLoggedIn = false;
  final city = 'Pokhara'; // cannot be reassigned
  const pi = 3.14;        // known at compile time

  print('$name is $age, lives in $city');
  print('Price with tax: ${price * 1.13}');
  print('$isLoggedIn $pi');
}

In Flutter you will see const everywhere: const Text('Hi'). It tells Flutter the widget never changes, which makes apps faster.

Functions and named parameters

Flutter widgets use named parameters (inside { }) all the time.

String greet(String name, {String greeting = 'Hello', bool shout = false}) {
  final text = '$greeting, $name!';
  return shout ? text.toUpperCase() : text;
}

void main() {
  print(greet('Ram'));
  print(greet('Sita', greeting: 'Namaste'));
  print(greet('Leo', shout: true));
}

That is exactly how Text('Hi', style: ...) or Padding(padding: ..., child: ...) work. required makes a named parameter compulsory: {required this.title}.

Arrow functions and callbacks

void main() {
  int square(int x) => x * x; // arrow = one-expression function
  print(square(4));

  void runTwice(void Function() action) {
    action();
    action();
  }

  runTwice(() => print('Tapped!')); // like onPressed: () => ...
}

onPressed: () { ... } in Flutter is just a function passed as a parameter.

Classes and constructors

Every widget is a class.

class Product {
  const Product({required this.name, required this.price, this.inStock = true});

  final String name;
  final double price;
  final bool inStock;

  String get label => '$name - \$${price.toStringAsFixed(2)}';
}

void main() {
  const p = Product(name: 'Coffee', price: 3.5);
  print(p.label);
  print(p.inStock);
}

Compare it with a widget: const MyButton({super.key, required this.label}); uses the same ideas.

Null safety

void main() {
  String? nickname;               // may be null
  print(nickname ?? 'No nickname');
  print(nickname?.length);        // null instead of a crash

  nickname = 'Bibek';
  print(nickname.length);         // safe now
}

You will see ?, ?? and ! in Flutter code, for example snapshot.data!. Read null safety for the details.

Lists, maps and collection for / if

void main() {
  final fruits = ['Apple', 'Mango', 'Banana'];
  final prices = {'Apple': 1.2, 'Mango': 2.5};
  final showMore = true;

  final labels = [
    for (final f in fruits) 'Fruit: $f', // collection for
    if (showMore) 'and more...',          // collection if
  ];

  print(labels);
  print(prices['Mango']);
  print(fruits.map((f) => f.length).toList());
}

In Flutter: children: [for (final item in items) Text(item)].

async and await

Loading data from the internet uses Future, async and await.

Future<String> fetchUser() async {
  await Future.delayed(const Duration(seconds: 1)); // pretend network call
  return 'Asha';
}

void main() async {
  print('Loading...');
  final user = await fetchUser();
  print('Hello, $user');
}

In Flutter you show this with a FutureBuilder.

Checklist before you start Flutter

  • I can write a class with a const constructor and named parameters.
  • I know what ?, ?? and ! mean.
  • I can loop over a list and use map.
  • I can pass a function as a parameter (() => ...).
  • I understand that await waits for a Future.

If you ticked them all, continue with your first Flutter app.

Try it yourself

Write a Student class with name and a list of marks, a getter average, and print every student whose average is 50 or more from a list of three students.

Practise in the playground Updated