Dart Cheat Sheet

Here’s a cheat sheet for Dart, a programming language primarily used for building mobile, web, and server applications with the Flutter framework:

Hello, World!

void main() {
  print('Hello, World!');
}

Variables and Data Types

Variable Declaration:

var variableName = 'value';

Data Types:

String name = 'Dart';
int age = 25;
double height = 5.9;
bool isStudent = true;

Control Flow

If-Else:

if (condition) {
  // code if true
} else {
  // code if false
}

Switch Case:

switch (variable) {
  case value1:
    // code
    break;
  case value2:
    // code
    break;
  default:
    // default code
}

For Loop:

for (var i = 0; i < 5; i++) {
  // code
}

While Loop:

while (condition) {
  // code
}

Functions

Function Declaration:

int add(int a, int b) {
  return a + b;
}

Arrow Functions:

int multiply(int a, int b) => a * b;

Lists

List Declaration:

List<int> numbers = [1, 2, 3, 4, 5];

Accessing List Elements:

var firstNumber = numbers[0];

Iterating Through List:

for (var number in numbers) {
  // code
}

Maps

Map Declaration:

Map<String, dynamic> person = {
  'name': 'John Doe',
  'age': 30,
  'isStudent': false,
};

Accessing Map Elements:

var personName = person['name'];

Classes and Objects:

class Person {
  String name;
  int age;

  // Constructor
  Person(this.name, this.age);

  // Method
  void greet() {
    print('Hello, $name!');
  }
}

void main() {
  var person = Person('John', 25);
  person.greet();
}

Exception Handling:

try {
  // code that might throw an exception
} catch (e) {
  // handle the exception
} finally {
  // code that runs whether an exception is thrown or not
}

Asynchronous Programming

Future and async/await:

Future<void> fetchData() async {
  // asynchronous code
}

Flutter-specific

Widgets and UI:

  • Container, Text, Column, Row, etc.

Stateful and Stateless Widgets:

class MyStatefulWidget extends StatefulWidget {
  @override
  _MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  // stateful widget code
}

Here is a dedicated Flutter Layout Cheat Sheet.

This cheat sheet covers basic Dart syntax and commonly used features. For more detailed information, refer to the Dart documentation. If you’re working with Flutter, also check the Flutter documentation.