[英]How can I simulate a tap event on a Flutter widget?
如何在 Flutter 小部件上模擬點擊事件?
例如,如何模擬點擊 Tabbar 標題? 更重要的是,我如何首先找到小部件? 請注意,我不想調用相關的回調,也不想使用 Flutter 測試類測試小部件,但我想在運行時模擬對小部件的點擊。
編輯 1:(請注意)我不想測試小部件或調用分配給 GestureDetector.onTap 或 RaisedButton.onPressed 等的方法...
首先,獲取RenderBox
。 然后只需調用hitTest
方法。 任何人都會這樣做,只要它安裝在樹上。
為此,您必須通過context.findRenderObject()
使用BuildContext
。
BuildContext context;
final renderObj = context.findRenderObject();
if (renderObj is RenderBox) {
final hitTestResult = HitTestResult();
if (renderObj.hitTest(hitTestResult, position: /* The offset where you want to "tap" */)) {
// a descendant of `renderObj` got tapped
print(hitTestResult.path);
}
}
如果小部件具有定義的 onTap 屬性,只需調用
widget.onTap();
使用GestureBinding
模擬屏幕任意位置的點擊事件:
完整示例:
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Column(
children: [
ElevatedButton(
onPressed: () {},
style: ElevatedButton.styleFrom(
primary: Colors.red[900],
),
child: SizedBox(
width: 400,
height: 400,
child: Center(child: Text("I'm a big button.")),
),
),
ElevatedButton(
onPressed: () async {
GestureBinding.instance!.handlePointerEvent(PointerDownEvent(
position: Offset(200, 300),
));
await Future.delayed(Duration(milliseconds: 500));
GestureBinding.instance!.handlePointerEvent(PointerUpEvent(
position: Offset(200, 300),
));
},
child: Text('Simulate Click'),
),
],
),
),
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.