The best explanation for the situation in which "The Star-Spangled Banner" was written is:
It was written during the defeat of the British at Fort McHenry.
Francis Scott Key composed the anthem after witnessing the bombardment of Fort McHenry by British forces during the War of 1812, specifically in September 1814. The sight of the American flag still flying after the battle inspired him to write the poem that would later become the national anthem.