我写的应用程序具有解锁手机计数器,我想在后台捕获事件按下按钮。当尝试事件按下时,计数器增加。

最佳答案

您可以使用HARDWARE_BUTTONS flutter包来执行此操作

https://pub.dev/packages/hardware_buttons#-readme-tab-看到这个

你可以像这样实现
导入'dart:async';

import 'package:hardware_buttons/hardware_buttons.dart' as HardwareButtons;

两倍= 0;
StreamSubscription<HardwareButtons.LockButtonEvent> _lockButtonSubscription;



_homeButtonSubscription = HardwareButtons.homeButtonEvents.listen((event) {
  setState(() {
    _latestHardwareButtonEvent = 'HOME_BUTTON';
    times=times+1;
  });
});

_lockButtonSubscription = HardwareButtons.lockButtonEvents.listen((event) {
  setState(() {
    _latestHardwareButtonEvent = 'LOCK_BUTTON';
  });
});


@override
void dispose() {
 super.dispose();
 _lockButtonSubscription?.cancel();
}

07-27 14:05