I can't get Scrolling Function to work on Appium Android

I am now getting the following error: An unknown server-side error occurred while processing the command. Original error: Cannot read properties of undefined (reading ‘element’)`

My code:

  async scrollDirection(startCoordinates: { x: number; y: number; }, endCoordinates: { x: number; y: number; }) {
    const touchActionPromise = driver.touchPerform([
      { action: 'press', startCoordinates },
      { action: 'moveTo', endCoordinates },
      { action: 'release' }
    ]);
    const timeoutPromise = new Promise((resolve) => setTimeout(resolve, 2000, 'Touch Action Timeout'));
    await Promise.race([touchActionPromise, timeoutPromise]);
  }

  async scrollIntoView(maximumScrolls = 2) {
    const scrollScreenSize = async (direction) => {
      const { width, height } = await driver.getWindowRect();
      const startCoordinates = { x: width / 2, y: height / 2 };
      let endCoordinates;
      const scrollRatio = 1.0; // Adjust this value to increase or decrease scroll length
      if (direction === 'down') {
        endCoordinates = { x: width / 2, y: height * (1 - scrollRatio) };
      } else if (direction === 'up') {
        endCoordinates = { x: width / 2, y: height * scrollRatio };
      }
      await this.scrollDirection(startCoordinates, endCoordinates);
    };

    let element = await $(this.selector);
    for (let scrolls = 0; scrolls < maximumScrolls; scrolls++) {
      if (await element.isDisplayed()) return; // Exit if element is visible
      const direction = scrolls < maximumScrolls / 2.5 ? 'down' : 'up';
      await scrollScreenSize(direction);
      element = await $(this.selector);
    }
    // If element not found after all scrolls
    throw Error(`Could not find screen element '${this.elementName}' while attempting to scroll the element into view, with the maximum retries of ${maximumScrolls}. Searching by selector: ${this.selector}`);
  }

I have tried with updrading and downgrading the version of the following: “appium”: “2.3.0”, “appium-uiautomator2-driver”: “2.37.0”,

Have tried changing the scrolling implementation, but always results in the same issue.

The code works perfectly fine for iOS.

So with a little bit more better debugging. I was able to find that the issue was with the version of appium-uiautomator2-driver.

Latest versions to work with touch are as follows:
“appium-uiautomator2-driver”: “2.30.0”,
“appium-xcuitest-driver”: “6.2.0”,

Anything later that does not work.