Google's language for Flutter apps. Fast, expressive, and compiles to native code for mobile, web, and desktop.
void main() is the entry point. var/late/final for variables. String interpolation with $ and ${}.
void main() {
print('Hello, World!');
String name = 'Mayank';
var age = 15;
print('$name is $age');
print('${name.toUpperCase()}');
final pi = 3.14; // can't reassign
late String data; // initialized later
data = 'now';
print(data);
}
void main() {
int age = 15;
double pi = 3.14;
String name = 'Mayank';
bool passed = true;
// Null safety
String? nullable = null;
print(nullable?.length ?? 0); // 0
// Collections
var nums = [1, 2, 3, 4, 5];
var map = {'a': 1, 'b': 2};
var set = {1, 2, 3};
// Spread operator
var more = [...nums, 6, 7];
print(more);
// Type inference
var x = 42; // int
var y = 3.14; // double
var z = 'hello'; // String
}
Named params with {}. Optional params. Arrow functions. Higher-order functions.
int add(int a, int b) => a + b;
String greet({required String name, String prefix = 'Hello'}) {
return '$prefix, $name!';
}
// Closures
var counter = 0;
void increment() => counter++;
void main() {
print(add(3, 4));
print(greet(name: 'Mayank'));
print(greet(name: 'World', prefix: 'Hi'));
increment();
increment();
print(counter); // 2
// Higher-order
var nums = [1, 2, 3, 4, 5];
print(nums.where((n) => n.isEven).toList());
print(nums.map((n) => n * 10).toList());
print(nums.fold(0, (a, b) => a + b));
}
if/else, switch (expression), for, while, for-in. Dart switches don't need break.
void main() {
var score = 85;
var grade = score >= 90 ? 'A' : score >= 80 ? 'B' : 'C';
print(grade);
// Switch expression
var day = 3;
var name = switch (day) {
1 => 'Monday',
2 => 'Tuesday',
3 => 'Wednesday',
_ => 'Other',
};
print(name);
// For loop
for (var i = 0; i < 5; i++) {
print(i);
}
// For-in
for (var n in [1, 2, 3, 4, 5]) {
print(n);
}
// While
var x = 0;
while (x < 5) {
print(x);
x++;
}
}
class Point {
double x, y;
Point(this.x, this.y);
Point.origin() : x = 0, y = 0;
Point.fromJson(Map<String, double> json)
: x = json['x'] ?? 0,
y = json['y'] ?? 0;
double distanceTo(Point other) {
var dx = x - other.x;
var dy = y - other.y;
return (dx * dx + dy * dy).sqrt();
}
}
void main() {
var p1 = Point(3, 4);
var p2 = Point.origin();
var p3 = Point.fromJson({'x': 1, 'y': 2});
print(p1.distanceTo(p2)); // 5.0
}
abstract class Shape {
double get area;
}
class Circle extends Shape {
double radius;
Circle(this.radius);
@override
double get area => 3.14159 * radius * radius;
}
class Rect extends Shape {
double w, h;
Rect(this.w, this.h);
@override
double get area => w * h;
}
mixin Drawable {
void draw() => print('Drawing: $runtimeType');
}
class Widget with Drawable {
String name;
Widget(this.name);
}
void main() {
var shapes = [Circle(5), Rect(4, 6)];
for (var s in shapes) {
print('${s.runtimeType} area=${s.area}');
}
Widget('button').draw();
}
import 'dart:async';
Future<String> fetchUser() async {
await Future.delayed(Duration(seconds: 1));
return 'Mayank';
}
Stream<int> countStream() async* {
for (var i = 1; i <= 5; i++) {
await Future.delayed(Duration(milliseconds: 500));
yield i;
}
}
void main() async {
// Future
var user = await fetchUser();
print('User: $user');
// Stream
await for (var n in countStream()) {
print(n);
}
// Stream operations
countStream()
.where((n) => n.isEven)
.map((n) => n * 10)
.listen((n) => print(n));
}
class Stack<T> {
final _items = <T>[];
void push(T item) => _items.add(item);
T pop() {
if (_items.isEmpty) throw StateError('Empty stack');
return _items.removeLast();
}
}
void main() {
// Error handling
try {
int.parse('not a number');
} on FormatException catch (e) {
print('Error: $e');
} finally {
print('Done');
}
// Generics
var stack = Stack<int>();
stack.push(1);
stack.push(2);
print(stack.pop());
var strings = Stack<String>();
strings.push('hello');
print(strings.pop());
}