Why do you add wp_footer() in footer file to add an admin bar in the top of the page?

The reason is because wp_footer() was the only place WordPress could output HTML into a theme when the admin bar was introduced.

The front-end output of themes is determined pretty much entirely by the theme, but WordPress needs to support themes and plugins loading their own scripts and styles. To support this WordPress added two functions in version 1.5 (2005): wp_head() and wp_footer(). Theme authors add these to their templates so that they, and plugin developers, can hook into them to add scripts and styles. wp_head() is placed between the <head> tags, for scripts that need to be loaded there, and wp_footer() gets put before the closing </body> tag (i.e. at the foot of the page), for scripts that need to be loaded there.

The admin bar was introduced in WordPress 3.1 (2011). The reason it uses wp_footer() is because at that time it was still the only way to add the HTML for the admin bar to the front end in a way that was compatible with existing themes. This means that the HTML for the admin bar is output at the bottom of the page, but CSS is used to position it at the top of the screen.

Theoretically WordPress could’ve required that theme developers add a new hook at the top of all pages, and output the admin bar there, but that would mean that none of the themes that were already available would be compatible.

Finally, in WordPress 5.2 (2019) a new function was introduced: wp_body_open(), which is placed at the very top, after <body>. This hook could be used to output the admin bar HTML at the top, but this has not been done, likely for backwards compatibility reasons, and because wp_body_open() is nowhere near as widely adopted as wp_footer() at this stage.

When it comes to developing a theme, wp_footer() is required for more than just the admin bar. It’s also required to support plugins loading their scripts at the bottom of the page. Since it’s been required for 15 years now, omitting it will prevent many plugins from working, not just the admin bar. This is in fact its main purpose, which is why it’s called wp_footer(), and not wp_header().