元数据(Metadata)

元数据使用注解为代码提供额外信息。

内置注解

class OldAPI {
  @deprecated
  void oldMethod() {
    print('此方法已弃用');
  }
  
  @Deprecated('请使用 newMethod() 代替')
  void anotherOldMethod() {
    print('使用新方法');
  }
}

class MyClass {
  @override
  String toString() {
    return 'MyClass 实例';
  }
}

自定义注解

class Todo {
  final String task;
  final String assignee;
  
  const Todo(this.task, this.assignee);
}

@Todo('实现功能', 'Alice')
class FeatureClass {
  @Todo('修复 bug', 'Bob')
  void buggyMethod() {
    // 实现
  }
}

常用注解

  • @override - 方法重写父类
  • @deprecated - 标记为已弃用
  • @pragma - 编译器提示
  • @immutable - 类应该是不可变的

下一步