检测用户何时未在 Flutter 中与应用程序交互 [英] Detect when user is not interacting the app in Flutter
问题描述
当用户 5 分钟未与应用交互时,我想显示一些屏幕保护程序类型的屏幕.那么有谁知道如何在颤振中实现这种功能.
I want to show some Screensaver type of screen when the user is not interacting the app for 5 minutes. So is anyone know how to achieve this kind of functionality in flutter.
import 'dart:async';
import 'package:flutter/material.dart';
const timeout = const Duration(seconds: 10);
const ms = const Duration(milliseconds: 1);
Timer timer;
void main() =>
runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
var home = MyHomePage(title: 'Flutter Demo Home Page');
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: home,
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _goToSecondScreen() {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => SecondPage()),
);
}
@override
Widget build(BuildContext context) {
return GestureDetector(child: Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Container(),
floatingActionButton: FloatingActionButton(
onPressed: _goToSecondScreen,
tooltip: 'Increment',
child: Icon(Icons.add),
),
), behavior:
HitTestBehavior.translucent, onTapDown: (tapdown) {
print("down");
if (timer != null) {
timer.cancel();
}
timer = startTimeout();
},);
}
startTimeout([int milliseconds]) {
var duration = milliseconds == null ? timeout : ms * milliseconds;
return new Timer(duration, handleTimeout);
}
void handleTimeout() {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => ScreenSaver()),
);
}
}
class SecondPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Container();
}
}
class ScreenSaver extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new GestureDetector(child:Container(color: Colors.yellow,),
onTap: (){
Navigator.pop(context);
},
);
}
}
这是我试图实现该功能的示例代码.当屏幕在第二个屏幕中处于活动状态时,它不工作并且 GestureDetector
停止侦听.
This is the sample code which I am trying to achieve the functionality. When the screen in active in Second screen its not working and the GestureDetector
stops listening.
推荐答案
你可以用 behavior 将你的整个应用包装在一个
接收触摸事件,同时允许应用中的小部件也接收这些触摸事件.GestureDetector
中:HitTestBehavior.translucent
You can wrap your whole app in a GestureDetector
with behavior:
HitTestBehavior.translucent
to receive touch events while allowing widgets in your app also receiving these touch events.
您可能还想收听键盘事件支持颤振的外部键盘
You might also want to listen to keyboard events External keyboard in flutter support
这篇关于检测用户何时未在 Flutter 中与应用程序交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!