Using GestureDetector

As the name implies, GestureDetector is a widget that detects gestures.

In the body of your layout, insert a GestureDetector. This widget has properties that respond to gestures of your user. You can respond to several user gestures. The most common ones include onTap, onDoubleTap, and onLongPress. Inside each of those gesture properties, you can add the code needed to respond to the user's gestures. Generally, what you'll do is change the state of the widget, but you are certainly not limited to that.

In our case, we'll need to move the bat, so the state value that will change is the left property of the positioned widget that contains the bat. We only need to respond to the horizontal drag, as the bat won't need to move vertically. Let's look at the steps to do that:

  1. In the build() method of pong.dart file, as a child of the batPositioned widget, let's add a GestureDetector, with an onHorizontalDragUpdate parameter. This will take a DragUpdateDetails object, which we can call update, containing information about the drag that's happening on the screen.
  2. Inside the function, we call a method called moveBat(), which will take the updated value:
Positioned(
bottom: 0,
left: batPosition,
child: GestureDetector(
onHorizontalDragUpdate: (DragUpdateDetails update)
=> moveBat(update),

child: Bat(batWidth, batHeight))
),
  1. Next, at the bottom of the _PongState class, write the moveBat() method:
void moveBat(DragUpdateDetails update) {
setState(() {
batPosition += update.delta.dx;
});
}

DragUpdateDetails has a delta property that contains the distance moved during the drag operation. dx is the horizontal delta. We just update the batPosition by adding the delta, which can be a positive or negative number.

If we try the app right now, we'll be able to move the bat horizontally across the screen.

Before giving the user the ability to interact with the game, let's override an important method in the _PongState class, which is dispose(): you should use it to release the resources used by the animation. In this case, the dispose() method will be automatically called when the _PongState object is discarded. Inside this method, we add a call to the dispose() method of the animation controller to prevent memory leaks:

@override
void dispose() {
controller.dispose();
super.dispose();
}

At this time, the ball and the bat are not linked in any way, but we're going to fix that next.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.234.188