I noticed that the build function was called twice in a stateless widget.
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
MyApp() {
print("constructor MyApp class");
}
@override
Widget build(BuildContext context) {
print("build MyApp");
return MaterialApp(
home: HomeWidget(),
);
}
}
class HomeWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(child: Text("home widget")),
);
}
}
console result
Performing hot restart...
Syncing files to device AOSP on IA Emulator...
Restarted application in 755ms.
I/flutter (14765): constructor MyApp class
I/flutter (14765): build MyApp
I/flutter (14765): build MyApp
From the console output, the constructor was called once and the build function was called twice.
I searched this issue and read documents below.
Why Root Widget gets build twice?
https://github.com/flutter/flutter/issues/33566
https://flutterigniter.com/future-async-called-multiple-times/
However, I don't understand clearly. Why is the build function called multiple times? I'm not using async or future, and my code is very simple.
This problem does not occur when running on dartpad. It only occurs in android studio.