什么是Overlay ,OverlayEntry,OverlayState
Overlay: 一个可以独立管理的Stack。 通过它让Widget浮在其他的Widget之上,从而实现悬浮窗效果。主要作用是通过内部的Stack来管理和叠放各个组件层,包括需要置顶的悬浮组件已经各中页面至今的切换。
OverlayEntry: 可以放在Overlay上的组件。OverlayEntry是通过build创建widget的,可以同过OverlayEntry的markNeedsBuild方法在下一帧重绘。
OverlayState:通过 Overlay.of(context).insert和 Overlay.of(context).insert()和OverlayEntry的remove()将OverlayEntry从Overlay上插入和移除。
Overlay一般不需要开发者手动创建,因为一般Flutter应用常见 的根 MaterialApp,WidgetsApp都会默认创建一个Navigator,而Navigator内部又会创建一个Overlay组件。
关系:
MaterialApp -> WidgetsApp -> Navigator -> Overlay
简单的使用
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData.light(),
home: const Home(),
);
}
}
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
@override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
OverlayEntry? _entry;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('OverlayEntry的使用'),
),
body: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
TextButton(
onPressed: () {
_entry = OverlayEntry(builder: (cxt) {
//可以看出内部使用的是Stack包裹的,可以使用Center将Container居中
return Positioned(
right: 100,
top: 100,
child: Container(
width: 100,
height: 100,
color: Colors.deepOrange,
));
});
Overlay.of(context)?.insert(_entry!);
},
style: ButtonStyle(
foregroundColor: ButtonStyleButton.allOrNull(Colors.white),
backgroundColor: ButtonStyleButton.allOrNull(Colors.green)),
child: const Text('添加')),
TextButton(
onPressed: () {
_entry?.remove();
},
style: ButtonStyle(
foregroundColor: ButtonStyleButton.allOrNull(Colors.white),
backgroundColor: ButtonStyleButton.allOrNull(Colors.red)),
child: const Text('移除')),
],
),
),
);
}
}
Loading组件的实现和分析
首先介绍一下MaterialApp和WidgetsApp的builder方法,我们可以通过这个方法创建属于自己的Overlay包裹住每个页面。
代码中的注释介绍
A builder for inserting widgets above the [Navigator] 用于在 [Navigator] 上方插入小部件的构建器
定义 一个OverlayEntry
//在Flutter3.0之后SchedulerBinding.instance就不是一个可空类型了,为了兼容3.0之前使用此方法
//https://docs.flutter.dev/development/tools/sdk/release-notes/release-notes-3.0.0
T? _ambiguate<T>(T? value) => value;
class CustomOverlayEntry extends OverlayEntry{
@override
CustomOverlayEntry({
required WidgetBuilder builder,
}) : super(builder: builder);
@override
void markNeedsBuild() {
//为了保证不在build阶段刷新OverlayEntry,具体的可阅读一下这篇文章
// https://book.flutterchina.club/chapter14/flutter_app_startup.html
if (_ambiguate(SchedulerBinding.instance)!.schedulerPhase ==
SchedulerPhase.persistentCallbacks) {
_ambiguate(SchedulerBinding.instance)!.addPostFrameCallback((_) {
super.markNeedsBuild();
});
} else {
super.markNeedsBuild();
}
}
}
创建一个Overlay
创建一个Overlay,通过MaterialApp的builder 方法,使能包裹住页面。
class CustomLoading extends StatefulWidget {
final Widget? child;
const CustomLoading({Key? key, required this.child}) : super(key: key);
@override
State<CustomLoading> createState() => _CustomLoadingState();
}
class _CustomLoadingState extends State<CustomLoading> {
late CustomOverlayEntry _entry;
@override
void initState() {
super.initState();
_entry = CustomOverlayEntry(
builder: (_) => LoadingManager.instance.widget ?? Container());
LoadingManager.instance.entry = _entry;
}
@override
Widget build(BuildContext context) {
return Material(
child: Overlay(
initialEntries: [
CustomOverlayEntry(
builder: (BuildContext context) {
if (widget.child != null) {
return widget.child!;
} else {
return Container();
}
},
),
_entry,
],
),
);
}
}
创建一个单例用来管理这个Overlay
class LoadingManager {
static final LoadingManager instance = LoadingManager._internal();
factory LoadingManager() {
return instance;
}
LoadingManager._internal();
CustomOverlayEntry? entry;
Widget? widget;
static TransitionBuilder builder({
TransitionBuilder? builder,
}) {
return (BuildContext context, Widget? child) {
if (builder != null) {
return builder(context, CustomLoading(child: child));
} else {
return CustomLoading(child: child);
}
};
}
static void show() {
instance.widget = Center(
child: Container(
color: Colors.amberAccent,
width: 60,
height: 60,
padding: EdgeInsets.all(10),
child: const CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation(Colors.green),
),
),
);
instance.entry?.markNeedsBuild();
}
static void dismiss() {
instance.widget = null;
instance.entry?.markNeedsBuild();
}
}
使用
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData.light(),
builder: LoadingManager.builder(),
home: const Home(),
);
}
}
class Home extends StatelessWidget {
const Home({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('自定义Loading'),
),
body: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
TextButton(
onPressed: () {
LoadingManager.show();
},
style: ButtonStyle(
foregroundColor: ButtonStyleButton.allOrNull(Colors.white),
backgroundColor: ButtonStyleButton.allOrNull(Colors.green)),
child: const Text('show')),
TextButton(
onPressed: () {
LoadingManager.dismiss();
},
style: ButtonStyle(
foregroundColor: ButtonStyleButton.allOrNull(Colors.white),
backgroundColor: ButtonStyleButton.allOrNull(Colors.red)),
child: const Text('dismiss')),
],
),
),
);
}
}