hit_testing_test.dart 2.51 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:flutter/gestures.dart';
6
import 'package:flutter/rendering.dart';
7
import 'package:flutter/widgets.dart';
8
import 'package:flutter_test/flutter_test.dart';
9 10 11

void main() {
  testWidgets('toString control test', (WidgetTester tester) async {
12
    await tester.pumpWidget(const Center(child: Text('Hello', textDirection: TextDirection.ltr)));
13
    final HitTestResult result = tester.hitTestOnBinding(Offset.zero);
14 15 16
    expect(result, hasOneLineDescription);
    expect(result.path.first, hasOneLineDescription);
  });
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43

  testWidgets('A mouse click should only cause one hit test', (WidgetTester tester) async {
    int hitCount = 0;
    await tester.pumpWidget(
      _HitTestCounter(
        onHitTestCallback: () { hitCount += 1; },
        child: Container(),
      ),
    );

    final TestGesture gesture =
        await tester.startGesture(tester.getCenter(find.byType(_HitTestCounter)), kind: PointerDeviceKind.mouse);
    await gesture.up();

    expect(hitCount, 1);
  });

  testWidgets('Non-mouse events should not cause movement hit tests', (WidgetTester tester) async {
    int hitCount = 0;
    await tester.pumpWidget(
      _HitTestCounter(
        onHitTestCallback: () { hitCount += 1; },
        child: Container(),
      ),
    );

    final TestGesture gesture =
44
        await tester.startGesture(tester.getCenter(find.byType(_HitTestCounter)));
45 46 47 48 49 50 51 52 53 54 55 56
    await gesture.moveBy(const Offset(1, 1));
    await gesture.up();

    expect(hitCount, 1);
  });
}


// The [_HitTestCounter] invokes [onHitTestCallback] every time
// [hitTestChildren] is called.
class _HitTestCounter extends SingleChildRenderObjectWidget {
  const _HitTestCounter({
57
    required Widget super.child,
58
    required this.onHitTestCallback,
59
  });
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85

  final VoidCallback? onHitTestCallback;

  @override
  _RenderHitTestCounter createRenderObject(BuildContext context) {
    return _RenderHitTestCounter()
      .._onHitTestCallback = onHitTestCallback;
  }

  @override
  void updateRenderObject(
    BuildContext context,
    _RenderHitTestCounter renderObject,
  ) {
    renderObject._onHitTestCallback = onHitTestCallback;
  }
}

class _RenderHitTestCounter extends RenderProxyBox {
  VoidCallback? _onHitTestCallback;

  @override
  bool hitTestChildren(BoxHitTestResult result, {required Offset position}) {
    _onHitTestCallback?.call();
    return super.hitTestChildren(result, position: position);
  }
86
}