1. Variables & Null Safety
// Type inference
var name = 'Flutter'; // String
final age = 25; // Immutable (runtime)
const pi = 3.14; // Immutable (compile-time)
// Null safety
String? nullableName; // Có thể null
String nonNullable = 'Hello'; // Không thể null
late String lazyInit; // Khởi tạo sau
// Null-aware operators
String display = nullableName ?? 'Default';
int? length = nullableName?.length;
nullableName ??= 'Fallback';
2. Classes & Mixins
class Product {
final String name;
final double price;
final String? description;
const Product({required this.name, required this.price, this.description});
Product copyWith({String? name, double? price}) {
return Product(name: name ?? this.name, price: price ?? this.price);
}
}
// Mixin
mixin Loggable {
void log(String message) => print('[${runtimeType}] $message');
}
// Abstract class
abstract class Repository {
Future> getAll();
Future getById(String id);
}
class ProductRepository extends Repository with Loggable {
@override
Future> getAll() async {
log('Fetching all products');
return [];
}
@override
Future getById(String id) async => null;
}
3. Collections & Pattern Matching
// Collections
final list = [1, 2, 3];
final set = {1, 2, 3};
final map = {'key': 'value', 'name': 'Dart'};
// Spread & collection if/for
final combined = [...list, if (true) 4, for (var i in [5, 6]) i];
// Records (Dart 3)
(String, int) userInfo = ('John', 25);
({String name, int age}) namedRecord = (name: 'John', age: 25);
// Pattern matching
switch (shape) {
case Circle(radius: var r) when r > 0:
print('Circle with radius $r');
case Rectangle(width: var w, height: var h):
print('Rectangle $w x $h');
}
4. Async/Await & Streams
// Future
Future<String> fetchData() async {
final response = await http.get(Uri.parse('https://api.example.com/data'));
return response.body;
}
// Stream
Stream<int> countStream(int max) async* {
for (var i = 0; i < max; i++) {
await Future.delayed(Duration(seconds: 1));
yield i;
}
}
// Listen
countStream(5).listen((value) => print(value));
Bài tiếp theo: Widget Tree & Basic Widgets.