Dynamics of magnetic fields of active regions in pre-flare states and during solar flares