Here’s a practical Dart cheat sheet for Flutter development, focused on the syntax and patterns you’ll use most often.
1. Variables
String name = 'Ganesh';
int age = 30;
double price = 99.50;
bool active = true;
Type inference
var name = 'Ganesh'; // inferred as String
var count = 10; // inferred as int
final vs const
final currentTime = DateTime.now();
const pi = 3.14159;
| Keyword | Meaning |
|---|
var | Type inferred |
final | Assigned once at runtime |
const | Compile-time constant |
2. Common Data Types
String name = 'Ganesh';
int quantity = 10;
double amount = 25.50;
bool enabled = true;
List<String> items = ['A', 'B'];
Set<int> ids = {1, 2, 3};
Map<String, dynamic> user = {
'name': 'Ganesh',
'age': 30,
};
3. String Operations
String firstName = 'Ganesh';
String lastName = 'Pillai';
Interpolation
String message = 'Hello $firstName';
String message2 = 'Hello ${firstName.toUpperCase()}';
Useful methods
name.length;
name.isEmpty;
name.isNotEmpty;
name.toUpperCase();
name.toLowerCase();
name.contains('Ganesh');
name.startsWith('G');
name.endsWith('h');
name.trim();
name.replaceAll('Ganesh', 'John');
4. Numbers
int a = 10;
int b = 3;
print(a + b);
print(a - b);
print(a * b);
print(a / b); // 3.333...
print(a ~/ b); // 3
print(a % b); // 1
Conversion:
int number = int.parse('100');
double price = double.parse('99.5');
String value = number.toString();
5. Null Safety
Dart uses null safety.
String name = 'Ganesh';
name cannot be null.
If null should be allowed:
String? name;
Null-aware operators
print(name?.length);
Use fallback value:
String displayName = name ?? 'Unknown';
Assign only if null:
name ??= 'Default';
Force non-null:
name!.length;
Be careful with !. You're telling Dart:
"Trust me, this value isn't null."
If you're wrong, you'll get a runtime error.
6. Conditions
int age = 20;
if (age >= 18) {
print('Adult');
} else {
print('Minor');
}
else if
if (score >= 90) {
print('A');
} else if (score >= 80) {
print('B');
} else {
print('C');
}
7. Comparison Operators
a == b
a != b
a > b
a < b
a >= b
a <= b
Logical operators:
&& // AND
|| // OR
! // NOT
Example:
if (age >= 18 && active) {
print('Allowed');
}
8. Ternary Operator
Instead of:
String result;
if (active) {
result = 'Active';
} else {
result = 'Inactive';
}
Use:
String result = active ? 'Active' : 'Inactive';
Very common in Flutter UI code.
Text(
active ? 'Enabled' : 'Disabled',
)
9. Switch
switch (status) {
case 'open':
print('Open');
break;
case 'closed':
print('Closed');
break;
default:
print('Unknown');
}
Dart also supports switch expressions:
final message = switch (status) {
'open' => 'Order is open',
'closed' => 'Order is closed',
_ => 'Unknown status',
};
10. Lists
Probably the collection you'll use most frequently.
List<String> products = [
'Laptop',
'Mouse',
'Keyboard',
];
Access:
products[0];
Add:
products.add('Monitor');
Remove:
products.remove('Mouse');
Useful operations:
products.length;
products.first;
products.last;
products.contains('Laptop');
products.isEmpty;
products.isNotEmpty;
11. Loop Through List
for (String product in products) {
print(product);
}
Or:
products.forEach((product) {
print(product);
});
You'll also frequently encounter:
products.map((product) {
return product.toUpperCase();
});
12. map()
Extremely important in Flutter.
List<int> numbers = [1, 2, 3];
var doubled = numbers.map((number) {
return number * 2;
}).toList();
Result:
[2, 4, 6]
You'll frequently see it when creating widgets:
Column(
children: products.map((product) {
return Text(product);
}).toList(),
)
13. Filtering Lists
Use where():
List<int> numbers = [10, 20, 30, 40];
var result = numbers
.where((number) => number > 20)
.toList();
Result:
[30, 40]
Very useful for filtering API/ERP data.
14. Maps
Dart maps are key/value structures.
Map<String, dynamic> salesOrder = {
'orderNumber': 'SO1001',
'customer': 'ABC Corp',
'amount': 5000.0,
'status': 'Open',
};
Access:
salesOrder['customer'];
Update:
salesOrder['status'] = 'Closed';
Add:
salesOrder['currency'] = 'INR';
Check:
salesOrder.containsKey('status');
15. Functions
Basic function:
void greet() {
print('Hello');
}
Return value:
int add(int a, int b) {
return a + b;
}
Call:
int result = add(10, 20);
16. Arrow Functions
Short functions can use =>.
int add(int a, int b) => a + b;
Instead of:
int add(int a, int b) {
return a + b;
}
You'll see arrow functions constantly in Flutter:
onPressed: () => print('Clicked')
17. Named Parameters
Very important because Flutter APIs use these heavily.
void createUser({
required String name,
required int age,
}) {
print(name);
}
Call:
createUser(
name: 'Ganesh',
age: 30,
);
This same pattern explains Flutter syntax like:
Text(
'Hello',
style: TextStyle(
fontSize: 20,
color: Colors.blue,
),
)
18. Optional Parameters
void greet({
required String name,
String greeting = 'Hello',
}) {
print('$greeting $name');
}
Usage:
greet(name: 'Ganesh');
or:
greet(
name: 'Ganesh',
greeting: 'Welcome',
);
19. Classes
class Customer {
String name;
int age;
Customer(this.name, this.age);
void display() {
print('$name - $age');
}
}
Create object:
var customer = Customer('ABC Corp', 10);
customer.display();
20. Named Constructor Parameters
Very common in Flutter code.
class Product {
final String name;
final double price;
Product({
required this.name,
required this.price,
});
}
Create:
final product = Product(
name: 'Laptop',
price: 50000,
);
21. Getters
class Product {
double price;
int quantity;
Product(this.price, this.quantity);
double get total => price * quantity;
}
Usage:
var product = Product(100, 5);
print(product.total);
22. Inheritance
class Animal {
void speak() {
print('Sound');
}
}
class Dog extends Animal {
@override
void speak() {
print('Woof');
}
}
23. Abstract Classes
abstract class PaymentService {
void pay(double amount);
}
Implementation:
class CardPayment implements PaymentService {
@override
void pay(double amount) {
print('Paid $amount');
}
}
24. Enums
Great for fixed business states.
enum OrderStatus {
open,
processing,
completed,
cancelled,
}
Usage:
OrderStatus status = OrderStatus.open;
if (status == OrderStatus.open) {
print('Order is open');
}
Prefer enums over strings such as:
status == 'Open'
when you control the model.
25. Exceptions
try {
int value = int.parse('abc');
} catch (e) {
print('Error: $e');
}
With finally:
try {
// execute
} catch (e) {
// handle error
} finally {
// always execute
}
Throw:
if (amount < 0) {
throw Exception('Amount cannot be negative');
}
26. Async / Await ⭐
Critical for Flutter apps communicating with APIs.
Future<String> getCustomer() async {
await Future.delayed(
Duration(seconds: 1),
);
return 'ABC Corp';
}
Call:
Future<void> loadData() async {
String customer = await getCustomer();
print(customer);
}
Think:
Future<T>
means:
"I will give you a T later."
Example:
Future<List<Product>>
means:
"This operation will eventually return a list of products."
27. Future Error Handling
A common API pattern:
Future<void> loadOrders() async {
try {
final orders = await getOrders();
print(orders);
} catch (e) {
print('Unable to load orders: $e');
}
}
This will be particularly important when you start calling REST/OData APIs from Flutter.
28. JSON
Typical API JSON:
{
"orderNumber": "SO1001",
"customer": "ABC Corp",
"amount": 5000
}
Dart:
Map<String, dynamic> json = {
'orderNumber': 'SO1001',
'customer': 'ABC Corp',
'amount': 5000,
};
Read:
json['orderNumber'];
json['customer'];
29. Model from JSON
This pattern is extremely useful for API-driven Flutter apps.
class SalesOrder {
final String orderNumber;
final String customer;
final double amount;
SalesOrder({
required this.orderNumber,
required this.customer,
required this.amount,
});
factory SalesOrder.fromJson(Map<String, dynamic> json) {
return SalesOrder(
orderNumber: json['orderNumber'],
customer: json['customer'],
amount: json['amount'].toDouble(),
);
}
}
Then:
final order = SalesOrder.fromJson(json);
Now:
print(order.orderNumber);
print(order.customer);
print(order.amount);
30. dynamic
dynamic value = 'Hello';
value = 100;
value = true;
Dart allows this, but avoid excessive use of dynamic.
Prefer:
String value = 'Hello';
because you get stronger compile-time checking and IDE assistance.
31. late
Tell Dart:
"This variable isn't initialized now, but I guarantee it will be initialized before use."
late String username;
void loadUser() {
username = 'Ganesh';
}
Common in Flutter, but use it carefully because accessing an uninitialized late variable causes a runtime error.
32. Cascade Operator ..
Lets you perform several operations on the same object.
Instead of:
var list = <String>[];
list.add('A');
list.add('B');
list.add('C');
You can write:
var list = <String>[]
..add('A')
..add('B')
..add('C');
33. Spread Operator ...
Combine collections:
var list1 = [1, 2, 3];
var list2 = [4, 5];
var all = [
...list1,
...list2,
];
Result:
[1, 2, 3, 4, 5]
This is very useful when constructing Flutter widget lists.
34. Collection if
Another very useful Flutter feature:
bool loggedIn = true;
var menu = [
'Home',
'Products',
if (loggedIn) 'Profile',
];
Flutter example:
Column(
children: [
Text('Home'),
if (loggedIn)
Text('Welcome back'),
],
)
35. Collection for
var numbers = [1, 2, 3];
var widgets = [
for (var number in numbers)
Text('$number'),
];
This becomes very convenient when dynamically generating UI.
36. Imports
Dart file:
import 'models/customer.dart';
Package:
import 'package:flutter/material.dart';
External package:
import 'package:http/http.dart' as http;
37. Private Members
In Dart, _ makes something library-private.
String _password = 'secret';
void _calculateTotal() {
// ...
}
You'll see this frequently with Flutter State:
class _HomePageState extends State<HomePage> {
}
38. Typedef
Useful for function signatures:
typedef Calculation = double Function(
double a,
double b,
);
Flutter uses callback-style concepts extensively.
For example:
final VoidCallback onPressed;
39. Records
Records allow multiple values to be grouped without creating a class.
(String, int) getUser() {
return ('Ganesh', 30);
}
Use:
var user = getUser();
print(user.$1);
print(user.$2);
Named fields are clearer:
({String name, int age}) getUser() {
return (
name: 'Ganesh',
age: 30,
);
}
Then:
var user = getUser();
print(user.name);
40. Pattern Matching
Modern Dart supports patterns.
var user = ('Ganesh', 30);
var (name, age) = user;
print(name);
print(age);
Very convenient when working with records and structured data.
41. Generic Classes
class ApiResponse<T> {
final T data;
ApiResponse(this.data);
}
Usage:
ApiResponse<String>(
'Success',
);
or:
ApiResponse<List<SalesOrder>>(
orders,
);
Generics become especially useful when building reusable API layers.
42. Dart → Flutter Mental Mapping
If you're learning Dart specifically for Flutter, remember these mappings:
| Dart concept | Flutter usage |
|---|
| Class | Widgets, models, services |
| Constructor | Widget configuration |
| Named parameter | Widget properties |
final | Widget/model fields |
| List | Collections of widgets/data |
| Map | JSON/API responses |
map() | Convert data into widgets |
where() | Filter data |
| Enum | Application/business states |
| Future | API/database operations |
async | Asynchronous operation |
await | Wait for API result |
| Null safety | Safer UI/API models |
try/catch | API error handling |
| Factory constructor | JSON → model |
| Inheritance | Widget/class specialization |
43. Flutter Code Becomes Easier Once You Read It as Dart
For example:
ElevatedButton(
onPressed: () {
print('Save');
},
child: const Text('Save'),
)
Break it down as Dart:
ElevatedButton(...)
│
└── Creating an object
onPressed:
│
└── Named parameter
() { }
│
└── Anonymous function
Text(...)
│
└── Another object
const
│
└── Compile-time constant
Likewise:
Column(
children: products
.map(
(product) => Text(product.name),
)
.toList(),
)
means conceptually:
List of Products → map() → convert each Product into a Text widget → List of Widgets → Column
The 80/20 for learning Dart
If your goal is Flutter application development, prioritize these first:
Must know: var / final / const → Null Safety → Lists & Maps → Functions → Named Parameters → Classes → map() / where() → JSON → Future → async/await → Exception Handling
Then move directly into Flutter:
Widgets → StatelessWidget → StatefulWidget → BuildContext → Layouts → Navigation → Forms → REST APIs → State Management
You don't need to master all of Dart before starting Flutter. Learning these concepts alongside a small Flutter application is generally much faster.
Comments
Post a Comment