Chuyển đến nội dung chính

第 2 課:Dart 語言深入探究

變數、類型、null 安全性、late 關鍵字。函數、閉包、擴充。類別、mixin、抽象類別。集合(列表、集合、映射)、模式匹配、記錄。非同步/等待、期貨、流。

💻 程式設計 — 第 2 課 第 2 課:Dart 語言深入探究

Flutter 和 Dart:從基礎到高級

第 1 部分:Dart 和 Flutter 基礎知識

亞洲開發網

1. 變數和空安全

// 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. 類別和混入

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
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. 非同步/等待和流

// 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));

下一篇: 小部件樹和基本小部件。