D
Flutter CoreBeginner10 XP2 min read

What is the role of main() and runApp() in a Flutter application?

TL;DR: main() is the Dart entry point; runApp() inflates the given widget as the root of the widget tree, initializes WidgetsFlutterBinding (connects Flutter framework to the engine), and schedules the first frame.

Full Answer

main() is where Dart execution begins. You call runApp() with your root widget. Internally, runApp() calls WidgetsFlutterBinding.ensureInitialized() (if not already done), attaches the widget to the screen, and triggers the first build pass.

💡

If you need to perform async initialization before runApp() (e.g., Firebase.initializeApp(), SharedPreferences.getInstance()), call WidgetsFlutterBinding.ensureInitialized() first to ensure the Flutter engine is ready before any binding operations.

Code Examples

dartmain() with async initialization
Output
Firebase initialized and orientation set before the first widget frame is built.

Interview Tip

💡

The classic mistake: calling SharedPreferences.getInstance() in main() without WidgetsFlutterBinding.ensureInitialized() — crashes because Flutter's platform channels aren't ready yet.

#main#runapp#entry-point#widgetsflutterbinding