**Nerd Alert**
It's to do with tempered tuning and pure tuning related to the harmonic series.
A modern piano (including synthesizers) are 'tempered' to make every octave 'sound' the same. So G major sounds identical to C major and to E. However the tempering means that things are always slightly out of tune to make it 'fit' the same sound.
With pure tuning using the natural harmonic series C major has a different 'sound/color' to F major and every other key. That is why composers used to compose in different keys and the key relationships between movements were also very important. A symphony in Bflat major had a very different impact on the listener to symphony in A major. These days, in many respects keys are superfluous.
To get back to you flattening your B in G major, you are flattened the 3rd of the chord which is what every major chord needs in order for it to have pure tuning. The 5th should be played slightly higher. In a minor chord however you have the raise the 3rd slightly to make the chord 'ring' or resonate. Dominant 7ths are the one that still to this day blow my mind as for it to really be in tune you end up lowering them almost a quarter tone flat.
It amazes me that the maths of the frequencies of the chords and the harmonic series is found all around us, in nature (spiral shells etc.) the golden mean, in space and the wider universe!!