5

When i was debugging why widgets are building again and again, and found this issue.

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print('Inside build');
    return MaterialApp( home: Container(child: Text('Hello World')));
 }
}

Output: flutter: Inside build

flutter: Inside build

Can someone explain why it printed twice? is it really rebuilding the MyApp() twice?

Flutter_Raj
  • 151
  • 2
  • 6
  • 1
    Idk but I tried this:void main() { print('Inside build'); runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Container(child: Text('Hello World'))); } } and run only once. – Emanuel Pele Jun 10 '20 at 20:10
  • It might be a double check to constructor or idk but main run only once. – Emanuel Pele Jun 10 '20 at 20:11
  • Can you please let me know what to check ? – Flutter_Raj Jun 10 '20 at 20:14
  • 1
    You are printing inside the build method which could run for many reasons. If you are doing hot reload it will run, but the main should be running once, you can add a print statement in main to confirm this. – Sami Haddad Jun 10 '20 at 20:15
  • 3
    You are correct, when i replace in main it printed only once but if it in first widget, it printed multiple times when started fresh. Any idea why it is printed multiple times ? – Flutter_Raj Jun 10 '20 at 20:19
  • Did your screen changed size or changed orientation? Any changes to the screen will trigger a rebuild. Have a read here: https://stackoverflow.com/questions/52249578/how-to-deal-with-unwanted-widget-build – digitaljoni Jun 11 '20 at 03:48

0 Answers0