Read the original article:How to Solve the Issue of Empty Screen Position During Drag Gesture
Problem Description
When implementing a PanGesture (drag gesture), using two fingers (performing a pinch-zoom gesture without adding a pinch gesture recognizer) can cause an unexpected crash.
Crash log:
Cannot read property displayX of undefined.
@Entry
@Component
struct Index {
@State touchX: number = 0;
@State touchY: number = 0;
build() {
Column() {
Column() {
}
.width(300)
.height(500)
.border({ width: 0.5, color: '#000' })
.gesture(
PanGesture()
.onActionStart((event: GestureEvent | undefined) => {
if (event && event.fingerList.length > 0) {
this.touchX = event.fingerList[0].displayX
this.touchY = event.fingerList[0].displayY
console.info(`fingerList: ${JSON.stringify(event.fingerList[0])}`)
// ...
}
})
.onActionUpdate((event?: GestureEvent | undefined) => {
if (event && event.fingerList.length > 0) {
this.touchX = event.fingerList[0].displayX
this.touchY = event.fingerList[0].displayY
console.info(`fingerList: ${JSON.stringify(event.fingerList[0])}`)
// ...
}
})
)
}
.height('100%')
.width('100%')
.padding(24)
}
}
Background Knowledge
PanGesture is used to trigger drag gesture events. The gesture is recognized when the sliding distance reaches the minimum threshold (default value is 5vp). The event parameter GestureEvent object contains a fingerList array that holds information for all touch points involved in the event.
Troubleshooting Process
According to the error message:
Cannot read property displayX of undefined
It indicates that event.fingerList[0] has no displayX property.
Analysis Conclusion
fingerList[0] may sometimes be undefined. For example, when operating with two fingers: after both the first and second fingers are pressed down, if the first finger is lifted first, fingerList[0] becomes null.
Solution
Add a conditional check to ensure that fingerList[0] is valid before accessing its properties.
Example code:
@Entry
@Component
struct Index {
@State touchX: number = 0;
@State touchY: number = 0;
build() {
Column() {
Column() {
}
.width(300)
.height(500)
.border({ width: 0.5, color: '#000' })
.gesture(
PanGesture()
.onActionStart((event: GestureEvent | undefined) => {
// Only get screen position when event.fingerList[0] has a value
if (event && event.fingerList.length > 0 && event.fingerList[0]) {
this.touchX = event.fingerList[0].displayX
this.touchY = event.fingerList[0].displayY
console.info(`fingerList: ${event.fingerList[0]}`)
// ...
}
})
.onActionUpdate((event?: GestureEvent | undefined) => {
// Only get screen position when event.fingerList[0] has a value
if (event && event.fingerList.length > 0 && event.fingerList[0]) {
this.touchX = event.fingerList[0].displayX
this.touchY = event.fingerList[0].displayY
console.info(`fingerList: ${JSON.stringify(event.fingerList[0])}`)
// ...
}
})
)
}
.height('100%')
.width('100%')
.padding(24)
}
}
Top comments (0)