FlyingOddo
FlyingOddo

Reputation: 55

How to test a LongPressDraggable in Flutter

I want to test a LongPressDraggable in Flutter. The WidgetTester provide methods like longPress or several drag methods. But there is no "longPressDrag" or something like this. The first idea was to run a longPress and a drag. But after the longPress the widget tester doesnt hold the widget and i can't drag it.

await tester.longPress(from);
await tester.timedDrag(from, offset, Duration(milliseconds: time));

A workaround is to use the timedDrag and run it super slow. This works but takes a lot of time.

await tester.timedDrag(from, offset, Duration(seconds: 15));

Is there a correct way to test the widget?

Upvotes: 2

Views: 1610

Answers (1)

passsy
passsy

Reputation: 5222

Use the startGesture method to start your own gesture. The "Finger is pressed" until you call geseture.up(). Between start and up use gesture.moveTo to move the cursor and tester.pump(duration) to stay still at a certain position to trigger the long-press.

Example code from the flutter repo in draggable_test.dart

    final Offset firstLocation = tester.getCenter(find.text('Source'));
    final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7);
    await tester.pump();

    expect(targetMoveCount['Target 1'], equals(0));
    expect(targetMoveCount['Target 2'], equals(0));

    final Offset secondLocation = tester.getCenter(find.text('Target 1'));
    await gesture.moveTo(secondLocation);
    await tester.pump();

    expect(targetMoveCount['Target 1'], equals(1));
    expect(targetMoveCount['Target 2'], equals(0));

    final Offset thirdLocation = tester.getCenter(find.text('Target 2'));
    await gesture.moveTo(thirdLocation);
    await tester.pump();

    expect(targetMoveCount['Target 1'], equals(1));
    expect(targetMoveCount['Target 2'], equals(1));

    await gesture.moveTo(secondLocation);
    await tester.pump();

    expect(targetMoveCount['Target 1'], equals(2));
    expect(targetMoveCount['Target 2'], equals(1));

    await gesture.up();
    await tester.pump();

Upvotes: 3

Related Questions