我想知道是否存在只要按下按鈕(任何型別的按鈕都可以)就可以在 Flutter 上連續呼叫函式的方法。
例如:
GestureDetector(
child: Container(),
onLongPressStart: () {}, // Start of the function
onLongPressEnd: () {}, // End of the function
)
uj5u.com熱心網友回復:
將您的更改onLongPressEnd為onLongPressUp. 所以它應該是這樣的:
GestureDetector(
child: Container(),
onLongPressStart: () {},
onLongPressUp: () {}
);
uj5u.com熱心網友回復:
你可以做類似的事情
- 長按,啟動計時器并呼叫函式
- 在長按結束時,停止計時器
例子:
Timer? timer;
GestureDetector(
onLongPressStart: (detail) {
setState(() {
timer = Timer.periodic(const Duration(milliseconds: 250), (t) {
print(Random().nextInt(1000) 9);
});
});
},
onLongPressEnd: (detail) {
if (timer != null) {
timer!.cancel();
}
},
child: Container(
child: const Text("press me"),
padding: const EdgeInsets.all(16),
color: kRedColor,
),
),
uj5u.com熱心網友回復:
您可以使用Timer這種情況。
//how often method will be called
Duration delay = const Duration(milliseconds: 100);
Timer? timer;
void continuousWork() {
debugPrint("I am working c ${timer!.tick}");
}
void onJobEnd() {
debugPrint("Job END");
timer?.cancel();
timer = null;
}
void onJobStart() {
if (timer != null) return;
debugPrint("Job started");
timer = Timer.periodic(delay, (timer) {
continuousWork();
});
}
用例將使用GestureDetector
GestureDetector(
onTap: () {},
onTapDown: (details) {
onJobStart();
},
onTapUp: (v) {
onJobEnd();
},
child: Text("tap"),
),
更多關于,以及使用
class _FpsPageState extends State<FpsPage> {
bool _shouldCount = false;
var _count = 0;
@override
Widget build(BuildContext context) {
if (_shouldCount) _count ;
return Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () {
_shouldCount = true;
_count = 0;
Timer.periodic(Duration(milliseconds: 1),(timer) {
setState(() {
if (timer.tick >= 1000) {
timer.cancel();
_shouldCount = false;
}
});
});
},
child: Text(_count != 0 ? 'FPS: $_count' : 'START'),
),
),
);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/491010.html
