flutter开发实战-当前界面无操作60s返回主页实现
当前界面无操作60s返回主页实现,主要是通过Timer来控制,当监听界面是否有pointerDown时候,如果超过60s仍没有操作,则返回主页。
一、Listener
Listener是用来用于调用回调以响应常见的指针事件
Listener的属性如下
const Listener({
super.key,
this.onPointerDown,
this.onPointerMove,
this.onPointerUp,
this.onPointerHover,
this.onPointerCancel,
this.onPointerPanZoomStart,
this.onPointerPanZoomUpdate,
this.onPointerPanZoomEnd,
this.onPointerSignal,
this.behavior = HitTestBehavior.deferToChild,
super.child,
}) : assert(behavior != null);
可以看出,我们可以通过onPointerDown来判断用户是否触摸到屏幕。
二、新增ListenerTouchTimerWrapper
为Widget添加Timer控制,当触摸了屏幕,取消Timer,重新倒计时。倒计时结束之后,可以执行callback。
void updateTouch() {
_timer?.cancel();
if (timeoutCallback != null) {
_timer = Timer(Duration(milliseconds: milliseconds), timeoutCallback!);
}
}
完整代码如下
class ListenerTouchTimer {
final int milliseconds;
Timer? _timer;
VoidCallback? timeoutCallback;
ListenerTouchTimer({
required this.milliseconds,
});
void startListener({required VoidCallback timeoutCallback}) {
this.timeoutCallback = timeoutCallback;
updateTouch();
}
void updateTouch() {
_timer?.cancel();
if (timeoutCallback != null) {
_timer = Timer(Duration(milliseconds: milliseconds), timeoutCallback!);
}
}
void dispose() {
_timer?.cancel();
}
}
为widget创建Wrapper
/// 无操作回主页
class ListenerTouchTimerWrapper extends StatelessWidget {
const ListenerTouchTimerWrapper({
super.key,
required this.child,
this.listenerTouchTimer,
});
final Widget child;
final ListenerTouchTimer? listenerTouchTimer;
@override
Widget build(BuildContext context) {
return Listener(
onPointerDown: (event) {
if (listenerTouchTimer != null) {
listenerTouchTimer!.updateTouch();
}
},
child: child,
);
}
}
三、使用ListenerTouchTimerWrapper
在界面的外层使用ListenerTouchTimerWrapper进行包裹一下。
class DemoPage extends StatefulWidget {
const DemoPage({
Key? key,
required this.arguments,
}) : super(key: key);
final Map<String, dynamic> arguments;
@override
State<DemoPage> createState() => _DemoPageState();
}
class _DemoPageState extends State<DemoPage> {
/// 超出60秒自动返回首页
ListenerTouchTimer? listenerTouchTimer;
@override
void initState() {
// TODO: implement initState
getAppConfigFromNative();
listenerTouchTimer = ListenerTouchTimer(milliseconds: 6000);
super.initState();
loggerInfo("ChangeClothe initState");
if (listenerTouchTimer != null) {
listenerTouchTimer!.startListener(timeoutCallback: () {
print("_ChangeClotheWaitPageState 超出60秒自动返回首页");
if (mounted ) {
navigatorBack();
}
});
}
}
@override
void dispose() {
// TODO: implement dispose
loggerInfo("ChangeClothe dispose");
listenerTouchTimer?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return ListenerTouchTimerWrapper(
listenerTouchTimer: listenerTouchTimer,
child: Scaffold(
body: Container(),
),
);
}
void navigatorBack() {
NavigatorPageRouter.pop();
}
}
四、小结
flutter开发实战-当前界面无操作60s返回主页实现
学习记录,每天不停进步。