Why doesn’t Mary know that she and Joseph must flee to Egypt?

Your question goes right to the heart of a crucial point about Mary: she was human, not divine. Being human, she did not have knowledge of the future in the way that God does. The message given by the angel during the Annunciation lets Mary know that her child will be the Son of God, so she knew that much, certainly. But there’s no evidence that she knew the details of how her life and her son’s life would unfold. She went on faith – a pretty astonishing faith, actually.

In his encyclical letter Redemptoris Mater, Pope John Paul II commented on the level of Mary’s faith and the extent to which she embraced the unknown:

“To believe means ‘to abandon oneself’ to the truth of the word of the living God, knowing and humbly recognizing ‘how unsearchable are his judgments and how inscrutable his ways’ (Romans 11:33). Mary, who by the eternal will of the Most High stands, one may say, at the very center of those ‘inscrutable ways’ and ‘unsearchable judgments’ of God, conforms herself to them in the dim light of faith, accepting fully and with a ready heart everything that is decreed in the divine plan.”