How do you reduce widget rebuild?
Using const widgets helps to avoid unnecessary rebuilds because the widgets are only built once and reused when the state changes.
import 'package:flutter/material.dart';class MyWidget extends StatefulWidget { @override _MyWidgetState createState() => _MyWidgetState();}class _MyWidgetState extends State<MyWidget> { bool _isSelected = false; @override Widget build(BuildContext context) { return Column( children: [ const SizedBox(height: 20), // const widget const Text('Click the button to change the state'), // const widget const SizedBox(height: 20), // const widget ElevatedButton( key: UniqueKey(), // unique key onPressed: () { setState(() { _isSelected = !_isSelected; }); }, child: const Text('Toggle State'), ), const SizedBox(height: 20), // const widget AnimatedBuilder( animation: _isSelected ? const AlwaysStoppedAnimation(1) : const AlwaysStoppedAnimation(0), builder: (context, child) { return Opacity( opacity: _isSelected ? 1 : 0, // shouldRebuild child: Container( color: Colors.red, height: 100, width: 100, ), ); }, ), ], ); }}
import 'package:flutter/material.dart';
class MyWidget extends StatefulWidget {
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
bool _isSelected = false;
Widget build(BuildContext context) {
return Column(
children: [
const SizedBox(height: 20), // const widget
const Text('Click the button to change the state'), // const widget
ElevatedButton(
key: UniqueKey(), // unique key
onPressed: () {
setState(() {
_isSelected = !_isSelected;
});
},
child: const Text('Toggle State'),
),
AnimatedBuilder(
animation: _isSelected
? const AlwaysStoppedAnimation(1)
: const AlwaysStoppedAnimation(0),
builder: (context, child) {
return Opacity(
opacity: _isSelected ? 1 : 0, // shouldRebuild
child: Container(
color: Colors.red,
height: 100,
width: 100,
);
],
With this technique you can help to reduce widget rebuilds in your Flutter app and improve its performance.