Today I came over following snippet of code that implements gradient in flutter
return new Container(
...
decoration: new BoxDecoration(
gradient: ne
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 {
String title = "Title";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Column(
children: [
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.
For more info: const constructors