Try not to use numbers in your program because the XIAO’s digital and analogue pin definitions do not match the GPIO’s pin numbering. For example D7 ≠ GPIO7.
If you want to connect the key to pin D2 of the XIAO and the LED to pin D7 of the XIAO, modify your programme like this.
const int buttonPin=D2;
const int ledPin=D7;
int buttonState=LOW;
void setup()
{
pinMode(D7,OUTPUT);
pinMode(D2,INPUT_PULLUP);
}
void loop()
{
buttonState=digitalRead(D2);
if(buttonState==HIGH)
{
digitalWrite(D7,HIGH);
delay(2000);
digitalWrite(D7,LOW);
}
}