说说Flutter中的Overlay
Overlay是什么
Flutter中的Overlay
是什么?先看看官方的文档注释吧:
/// A [Stack] of entries that can be managed independently.
///
/// Overlays let independent child widgets "float" visual elements on top of
/// other widgets by inserting them into the overlay's [Stack]. The overlay lets
/// each of these widgets manage their participation in the overlay using
/// [OverlayEntry] objects.
简单总结一下,Overlay
是一个可以管理的堆栈。我们可以通过将一个Widget
插入这个堆栈中,这样就可以让此Widget
浮在其他的Widget
之上,从而实现悬浮窗效果。我们可以通过OverlayEntry
对象的配置来管理Overlay
的层级关系。
通过追踪构造方法,我们可以发现它被Navigator
所创建,而Navigator
又被WidgetsApp
所创建。通常我们runApp
启动的page里会创建的CupertinoApp
或者MaterialApp
都会创建WidgetsApp
,因此我们在项目中可以直接使用这个创建好的Overlay
。
简单使用
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback(
(timeStamp) {
OverlayEntry entry = OverlayEntry(
builder: (_) {
return IgnorePointer(
child: Center(
child: Text('OverlayEntry'),
),
);
},
);
Overlay.of(context).insert(entry);
},
);
}
Overlay
的使用很简单,通过Overlay.of(context)
方法向上查找到OverlayState
,然后通过insert
或者insertAll
方法插入一个或多个悬浮Widget
。如果想要移除此悬浮Widget
,我们可以通过OverlayEntry
的remove()
方法实现。
Overlay原理源码解析
为什么Overlay
插入的OverlayEntry
会在页面上面悬浮呢?先来看看insert
方法做了什么:
void insert(OverlayEntry entry, { OverlayEntry below, OverlayEntry above }) {
...
entry._overlay = this;
setState(() {
_entries.insert(_insertionIndex(below, above), entry);
});
}
可以看到OverlayEntry
被插入了_entries
中的指定位置,再看_insertionIndex
的实现:
int _insertionIndex(OverlayEntry below, OverlayEntry above) {
assert(above == null || below == null);
if (below != null)
return _entries.indexOf(below);
if (above != null)
return _entries.indexOf(above) + 1;
return _entries.length;
}
我们没有指定可选参数的时候,默认会将OverlayEntry
插入到_entries
的末端。再看看OverlayState
的build
方法:
@override
Widget build(BuildContext context) {
// This list is filled backwards and then reversed below before
// it is added to the tree.
final List<Widget> children = <Widget>[];
bool onstage = true;
int onstageCount = 0;
for (int i = _entries.length - 1; i >= 0; i -= 1) {
final OverlayEntry entry = _entries[i];
if (onstage) {
onstageCount += 1;
children.add(_OverlayEntryWidget(
key: entry._key,
entry: entry,
));
if (entry.opaque)
onstage = false;
} else if (entry.maintainState) {
children.add(_OverlayEntryWidget(
key: entry._key,
entry: entry,
tickerEnabled: false,
));
}
}
return _Theatre(
skipCount: children.length - onstageCount,
children: children.reversed.toList(growable: false),
);
}
build
中会倒序遍历_entries
,然后生成一个个_OverlayEntryWidget
,最后这个列表又会被倒序放入_Theatre
这个控件中。那这个_Theatre
是什么呢?
/// Special version of a [Stack], that doesn't layout and render the first
/// [skipCount] children.
///
/// The first [skipCount] children are considered "offstage".
class _Theatre extends MultiChildRenderObjectWidget
@protected
void paintStack(PaintingContext context, Offset offset) {
RenderBox child = _firstOnstageChild;
while (child != null) {
final StackParentData childParentData = child.parentData as StackParentData;
context.paintChild(child, childParentData.offset + offset);
child = childParentData.nextSibling;
}
}
@override
void paint(PaintingContext context, Offset offset) {
if (_hasVisualOverflow) {
context.pushClipRect(needsCompositing, offset, Offset.zero & size, paintStack);
} else {
paintStack(context, offset);
}
}
paint
很简单,他会从第一个child开始循环绘制,也就是说children
会被一层一层的绘制在屏幕上,那么我们最后插入的OverlayEntry
自然是在最上了。
可能到这里还是会有疑惑,插入的OverlayEntry
只是在众多的OverlayEntry
当中的最上,为啥会在各个页面之上呢?其实到这里也可以大概才出原因了:
/// Although you can create an [Overlay] directly, it's most common to use the
/// overlay created by the [Navigator] in a [WidgetsApp] or a [MaterialApp]. The
/// navigator uses its overlay to manage the visual appearance of its routes.
Overlay
的注释中还有这么一段:The navigator uses its overlay to manage the visual appearance of its routes.
,所以,我们的各个页面其实也是一个个OverlayEntry
,Navigator
的源码还是比较绕的,追踪源码看看:
@optionalTypeArgs
Future<T> push<T extends Object>(Route<T> route) {
...
_history.add(_RouteEntry(route, initialState: _RouteLifecycle.push));
_flushHistoryUpdates();
...
_afterNavigation(route);
return route.popped;
}
当我们执行Navigator
的push
方法后,会先放_history中增加一条路由记录,然后执行 _flushHistoryUpdates
方法:
void _flushHistoryUpdates({bool rearrangeOverlay = true}) {
int index = _history.length - 1;
...
final List<_RouteEntry> toBeDisposed = <_RouteEntry>[];
while (index >= 0) {
switch (entry.currentState) {
...
case _RouteLifecycle.push:
case _RouteLifecycle.pushReplace:
case _RouteLifecycle.replace:
assert(rearrangeOverlay);
entry.handlePush(
navigator: this,
previous: previous?.route,
previousPresent: _getRouteBefore(index - 1, _RouteEntry.isPresentPredicate)?.route,
isNewFirst: next == null,
);
assert(entry.currentState != _RouteLifecycle.push);
assert(entry.currentState != _RouteLifecycle.pushReplace);
assert(entry.currentState != _RouteLifecycle.replace);
if (entry.currentState == _RouteLifecycle.idle) {
continue;
}
break;
...
case _RouteLifecycle.disposed:
case _RouteLifecycle.staging:
assert(false);
break;
}
index -= 1;
next = entry;
entry = previous;
previous = index > 0 ? _history[index - 1] : null;
}
...
if (rearrangeOverlay)
overlay?.rearrange(_allRouteOverlayEntries);
}
_flushHistoryUpdates
方法很长,这里看要点,push
方法执行后会加入的_RouteEntry
,会执行handlePush
方法,handlePush
方法会执行Route
的install
方法,看看我们常用的MaterialPageRoute
的继承关系:

藏得真的深,我们可以发现MaterialPageRoute
有一个父类OverlayRoute
,看看OverlayRoute
中的install
方法:
@override
void install() {
assert(_overlayEntries.isEmpty);
_overlayEntries.addAll(createOverlayEntries());
super.install();
}
install
方法会执行createOverlayEntries
方法生成Iterable<OverlayEntry>
并加入列表。到这里我们也大概可以搞清楚了,push
一个页面本质上还是push
了一个OverlayEntry
。_flushHistoryUpdates
方法最终会调用OverlayState
的rearrange
方法处理列表:
void rearrange(Iterable<OverlayEntry> newEntries, { OverlayEntry below, OverlayEntry above }) {
final List<OverlayEntry> newEntriesList = newEntries is List<OverlayEntry> ? newEntries : newEntries.toList(growable: false);
...
if (newEntriesList.isEmpty)
return;
if (listEquals(_entries, newEntriesList))
return;
final LinkedHashSet<OverlayEntry> old = LinkedHashSet<OverlayEntry>.from(_entries);
for (final OverlayEntry entry in newEntriesList) {
entry._overlay ??= this;
}
setState(() {
_entries.clear();
_entries.addAll(newEntriesList);
old.removeAll(newEntriesList);
_entries.insertAll(_insertionIndex(below, above), old);
});
}
rearrange
方法会先复制一遍旧的_entries
列表,然后清空_entries
列表,加入最新的路由列表数据,再从旧列表中去重路由列表,这样剩下的基本都是用户自己insert的OverlayEntry
,最后再将旧列表的数据插入新的列表,这样用户的OverlayEntry
还是会在各个页面的上层。
转载自:https://juejin.cn/post/6904604605028990983