检测用户何时未在Flutter中交互应用程序

问题描述 投票:2回答:1

我希望在用户未与应用程序交互5分钟时显示一些屏幕保护程序类型的屏幕。所以有人知道如何在颤动中实现这种功能。

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停止收听。

flutter flutter-layout
1个回答
2
投票

您可以使用GestureDetector将整个应用程序包装在behavior: HitTestBehavior.translucent中以接收触摸事件,同时允许应用程序中的小部件也接收这些触摸事件。

您可能还想听键盘事件External keyboard in flutter support

© www.soinside.com 2019 - 2024. All rights reserved.