Flutter随笔

Flutter Tips记录

2019-11-09  本文已影响0人  嘛尼嘛哄

1. 访客模式

void visitChildren(ElementVisitor visitor)

//case1: 查找最近的RenderObject
  RenderObject get renderObject {
    RenderObject result;
    void visit(Element element) {
      assert(result == null); // this verifies that there's only one child
      if (element is RenderObjectElement)
        result = element.renderObject;
      else
        element.visitChildren(visit);
    }
    visit(this);
    return result;
  }

2. 锁

lass _InactiveElements {
  bool _locked = false;
  final Set<Element> _elements = HashSet<Element>();

  void _unmountAll() {
    _locked = true;
    
    final List<Element> elements = _elements.toList()..sort(Element._sort);
    _elements.clear();
    try {
      elements.reversed.forEach(_unmount);
    } finally {
      assert(_elements.isEmpty);
      _locked = false;
    }
  }

  void add(Element element) {
    assert(!_locked);
     ..

  void remove(Element element) {
    assert(!_locked);
    ...
}

3.多重继承模式

class WidgetsFlutterBinding extends BindingBase with GestureBinding, ServicesBinding, SchedulerBinding, PaintingBinding, SemanticsBinding, RendererBinding, WidgetsBinding {
  ...
  static WidgetsBinding ensureInitialized() {
    if (WidgetsBinding.instance == null)
      WidgetsFlutterBinding();
    return WidgetsBinding.instance;
  }
}

mixin GestureBinding on BindingBase implements HitTestable, HitTestDispatcher, HitTestTarget {
  @override
  void initInstances() {
    super.initInstances();
    _instance = this;
    window.onPointerDataPacket = _handlePointerDataPacket;
  }
... 

void main() {
  final perosnal = Personal();
}

abstract class PersonalAbstract {
  PersonalAbstract() {
    print('PersonalAbstract sleep start');
    sleep();
    print('PersonalAbstract sleep end');
  }
  void sleep() {
    print('PersonalAbstract sleep');
  }
}

class Personal extends PersonalAbstract with mixin1, mixin2, mixin3 {}

mixin mixin1 on PersonalAbstract {
  @override
  void sleep() {
    super.sleep();
    print('mixin1 sleep');
  }
}

mixin mixin2 on PersonalAbstract {
  @override
  void sleep() {
    super.sleep();
    print('mixin2 sleep');
  }
}

mixin mixin3 on PersonalAbstract {
  @override
  void sleep() {
    super.sleep();
    print('mixin3 sleep');
  }
}

/*
输出顺序如下,其中override改写多次,只执行了一次,推测应该是内部做了优化去重。
PersonalAbstract sleep start
PersonalAbstract sleep
mixin1 sleep
mixin2 sleep
mixin3 sleep
*/

4. 单利

abstract class Zone {
  Zone._();
  static const Zone root = _rootZone;
  static Zone _current = _rootZone;

5. 数组获取

  operator [](Object key) => null;
上一篇下一篇

猜你喜欢

热点阅读