[英]long press for incrementing value
我有一個帶有回調 function 的增量按鈕:
class IncrementButton extends StatelessWidget {
final VoidCallback callback;
const IncrementButton({
Key? key,
required this.callback,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
callback();
},
onLongPressStart: ((details) {
callback();
}),
......
);
}
}
並將其用作:
IncrementButton(
callback: _increment,
),
_increment function 為:
_increment() {
value += 1;
}
我想要的是當用戶點擊一次時,_increment function 將被調用。 但是當用戶長按按鈕時,應該調用相同的增量 function。 但這不會發生。 _increment
方法只被長時間調用一次
我猜您希望在長按按鈕/容器的同時不斷增加數字。 您需要一個在調用onLongPress
時啟動的計時器。 當調用“onLongPressEnd”時,計時器停止。
嘗試這個:
import 'dart:async';
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String action = "START";
Timer? timer;
int number = 0;
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Material App',
home: Scaffold(
appBar: AppBar(
title: const Text('Material App Bar'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(action),
SizedBox(height: 50),
Material(
borderRadius: BorderRadius.circular(20),
elevation: 20,
child: GestureDetector(
onTap: () => setState(() {
action = "Tap";
number++;
}),
onLongPress: () => setState(() {
timer = Timer.periodic(Duration(milliseconds: 50), (timer) {
setState(() {
action = "Longpress started";
number++;
});
});
}),
onLongPressEnd: (_) => setState(() {
action = "Longpress stopped";
timer?.cancel();
}),
child: Container(
alignment: Alignment.center,
decoration: BoxDecoration(
color: Colors.red[50],
borderRadius: BorderRadius.circular(20)
),
width: 100,
height: 100,
child: Text('Tap')
),
),
),
SizedBox(height: 50,),
Text(number.toString())
],
),
),
),
);
}
@override
void dispose() {
timer?.cancel();
super.dispose();
}
}
更改您的 onlongpressStart。
do{
callback();
} while(btnPressed);
在 onlongpressEnd
setState(() => btnPressed = false);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.