In React, when a parent is being re-rendered, but one of its subcomponent’s inputs do not change, the build method in the subcomponent is not called. However in Flutter, it seems that all children are re-rendered on every state change. Isn’t this inefficient? What is the purpose of calling the build method when the inputs haven’t changed? Can I prevent this behaviour?
In the following example I expect the counter to increment every 2 seconds, and a new random number to also be generated every 2 seconds, instead of every second which is what I see.
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
int value = 0;
@override
void initState() {
super.initState();
Timer.periodic(Duration(seconds: 1), (timer) {
// The subclass widget rebuilds after updating state,
// even though none of its inputs change
setState(() {});
});
Timer.periodic(Duration(seconds: 2), (timer) {
// I only want the component to be rebuilt here when one of the inputs of subclass rebuilds
setState(() {
value++;
});
});
}
@override
Widget build(BuildContext context) {
return Subclass(
value: value,
);
}
}
class Subclass extends StatelessWidget {
final int value;
Subclass({
Key? key,
required this.value,
}) : super(key: key);
@override
Widget build(BuildContext context) {
print("I am re-building the widget $value!");
expensiveComputation() {
print("I am doing an expensive computation!");
return Random().nextInt(1000);
}
final expensiveComputationRes = expensiveComputation();
return Text(
'Hello, World! $value $expensiveComputationRes',
textDirection: TextDirection.ltr,
);
}
}