Flutter external factory 关键字的作用

15 min read

external只声明方法,声明的方法需要由外部去实现,通常是由底层sdk根据不同平台(vm、web等)实现;若外部没实现,则会返回null

external声明的方法,通过@patch注解实现

Object里各种external声明方法的实现如下:

@patch
class Object {
  ...
  @patch
  bool operator ==(Object other) native "Object_equals";

  static final _hashCodeRnd = new Random();

  static int _objectHashCode(obj) {
    var result = _getHash(obj);
    if (result == 0) {
      // We want the hash to be a Smi value greater than 0.
      result = _hashCodeRnd.nextInt(0x40000000);
      do {
        result = _hashCodeRnd.nextInt(0x40000000);
      } while (result == 0);
      _setHash(obj, result);
    }
    return result;
  }

  @patch
  int get hashCode => _objectHashCode(this);
  

  @patch
  String toString() native "Object_toString";

  @patch
  @pragma("vm:exact-result-type", "dart:core#_Type")
  Type get runtimeType native "Object_runtimeType";
  ...
}