116 lines
2.8 KiB
Dart
116 lines
2.8 KiB
Dart
import 'package:flutter/material.dart';
|
||
import 'package:sensors_plus/sensors_plus.dart';
|
||
import 'package:vibration/vibration.dart';
|
||
import 'dart:async';
|
||
import './record_page.dart';
|
||
|
||
class HomePage extends StatefulWidget {
|
||
const HomePage({Key? key}) : super(key: key);
|
||
|
||
@override
|
||
State<HomePage> createState() => _HomePageState();
|
||
}
|
||
|
||
class _HomePageState extends State<HomePage> {
|
||
StreamSubscription? _accelerometerSubscription;
|
||
DateTime? _lastShakeTime;
|
||
int _shakeCount = 0;
|
||
bool _isNavigating = false;
|
||
|
||
@override
|
||
void initState() {
|
||
super.initState();
|
||
_initShakeDetection();
|
||
}
|
||
|
||
/// 初始化摇晃检测
|
||
void _initShakeDetection() {
|
||
_accelerometerSubscription = accelerometerEvents.listen((event) {
|
||
// 主要检测左右摇晃(x轴)
|
||
if (event.x.abs() > 25) {
|
||
final now = DateTime.now();
|
||
if (_lastShakeTime == null) {
|
||
_lastShakeTime = now;
|
||
_shakeCount = 1;
|
||
} else {
|
||
// 缩短有效时间窗口,要求更快的摇晃
|
||
if (now.difference(_lastShakeTime!) < const Duration(milliseconds: 500)) {
|
||
_shakeCount++;
|
||
if (_shakeCount >= 2) {
|
||
_navigateToRecordPageWithVibration();
|
||
_shakeCount = 0;
|
||
_lastShakeTime = null;
|
||
}
|
||
} else {
|
||
// 重置计数
|
||
_shakeCount = 1;
|
||
}
|
||
_lastShakeTime = now;
|
||
}
|
||
}
|
||
});
|
||
}
|
||
|
||
/// 通过摇晃触发的导航(带震动)
|
||
void _navigateToRecordPageWithVibration() async {
|
||
if (_isNavigating) return;
|
||
|
||
_isNavigating = true;
|
||
// 添加震动反馈
|
||
if (await Vibration.hasVibrator() ?? false) {
|
||
Vibration.vibrate(duration: 200);
|
||
}
|
||
|
||
Navigator.push(
|
||
context,
|
||
MaterialPageRoute(
|
||
builder: (context) => const RecordPage(),
|
||
maintainState: false,
|
||
),
|
||
).then((_) {
|
||
_isNavigating = false;
|
||
});
|
||
}
|
||
|
||
/// 通过按钮触发的导航(无震动)
|
||
void _navigateToRecordPage() {
|
||
if (_isNavigating) return;
|
||
|
||
_isNavigating = true;
|
||
Navigator.push(
|
||
context,
|
||
MaterialPageRoute(
|
||
builder: (context) => const RecordPage(),
|
||
maintainState: false,
|
||
),
|
||
).then((_) {
|
||
_isNavigating = false;
|
||
});
|
||
}
|
||
|
||
@override
|
||
void dispose() {
|
||
_accelerometerSubscription?.cancel();
|
||
super.dispose();
|
||
}
|
||
|
||
@override
|
||
Widget build(BuildContext context) {
|
||
return Scaffold(
|
||
appBar: AppBar(
|
||
title: const Text('记账本'),
|
||
),
|
||
body: Center(
|
||
child: Column(
|
||
mainAxisAlignment: MainAxisAlignment.center,
|
||
children: [
|
||
ElevatedButton(
|
||
onPressed: _navigateToRecordPage,
|
||
child: const Text('记账'),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
);
|
||
}
|
||
} |