Pedro Massango
Posted on September 7, 2019
When we use setState()
Flutter calls the build method and rebuilds every widget tree inside it. The best way to avoid this is by using const costructors.
Use const constructors whenever possible when building your own widgets or using Flutter widgets. This helps Flutter to rebuild only widgets that should be updated.
So if you have a StatefulWidget
and you are using setState((){})
to update that widget and you have widgets like:
class _MyWidgetState extends State<MyWidget> {
String title = "Title";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Column(
children: <Widget>[
const Text("Text 1"),
const Padding(
padding: const EdgeInsets.all(8.0),
child: const Text("Another Text widget"),
),
const Text("Text 3"),
],
),
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.add),
onPressed: () {
setState(() => title = 'New Title');
},
),
);
}
}
If you run this code and press the floating action button, all the widgets defined as const won't get rebuilded.
💖 💪 🙅 🚩
Pedro Massango
Posted on September 7, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.