findTouchedWidget static method
Use HitBox test to find touched item on the screen.
Since the results are just a list of RenderObjects, we'll need to parse the Widget info.
Implementation
static String findTouchedWidget(
final BuildContext context, final Offset position) {
String jsonString = "";
final RenderObject? renderObject = context.findRenderObject();
if (renderObject is RenderBox) {
final RenderBox renderBox = renderObject;
final Size widgetSize = renderBox.size;
print('Widget size: $widgetSize');
final Offset localOffset = renderBox.globalToLocal(position);
print(renderBox);
// Perform hit-testing
final BoxHitTestResult result = BoxHitTestResult();
renderBox.hitTest(result, position: localOffset);
// Analyze the hit result to find the widget that was touched.
for (HitTestEntry entry in result.path) {
if (entry is! BoxHitTestEntry || entry is SliverHitTestEntry) {
final targetWidget = entry.target;
final widgetString = targetWidget.toString();
jsonString = jsonEncode(widgetString);
break;
}
}
}
return jsonString == "" ? "FlutterSurfaceView" : jsonString;
}