Preference not working when pressing button in esp32

I am working on a counter project using esp32 in which I want to store the value of counter in esp32 using preferences library when a button is pressed. It works when the code is

#include <Arduino.h>
#include<Preferences.h>

Preferences preferences;

int val = 0;
void setup(){
         Serial.begin(115200);
         preferences.begin("counter", false);
         val = preferences.getUInt("val",0);
         val++;
         Serial.println(val);
         preferences.putUInt("val",val);
}
void loop(){
}

It doesn’t work when the code is

#include <Arduino.h>
#include<Preferences.h>

Preferences preferences;
#define reset 26

void save();

int val = 0,flag = 0;
void setup(){
       Serial.begin(115200);
       pinMode(reset, INPUT_PULLUP);
       preferences.begin("counter", false);
       val = preferences.getUInt("val",0);
       val++;
       Serial.println(val);
}
void loop(){
        if(digitalRead(reset) == 0){
        save();
       }
}
void save(){
        if(flag==0){
           preferences.putUInt("val", val);
           flag++;
        }
}

I am using platformio and android framework

What’s the behavior of the sketch and what’s the expected behavior of the sketch

I have edited the code to store the value when the button is being pressed, and I want to do it only once for testing purposes. but it is not storing