Flutter Tips记录
2019-11-09 本文已影响0人
嘛尼嘛哄
1. 访客模式
- 查找最近的RenderObjectElement
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. 锁
- flutter是单线程的,在
_InactiveElements
,在对Element进行装配的过程层中使用了实例变量_lock
来控制
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.多重继承模式
- 通过 abstract抽象实现,子类mixn多个类同时重写它的抽象父类来完成
- App启动时初始化FlutterEngine的绑定事件就充分应用了这一点
- 具体代码实现,通过
initInstances();
方法混入了多个类的实现,非常有效的将各个Service的绑定逻辑分散到各自的类中
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. 单利
- 将默认的构造方法私有化, 在flutter中使用
_
修饰私有变量和方法。
abstract class Zone {
Zone._();
static const Zone root = _rootZone;
static Zone _current = _rootZone;
5. 数组获取
operator [](Object key) => null;