How do you reduce widget rebuild?
Loading
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;@overrideWidget build(BuildContext context) {return Column(children: [const SizedBox(height: 20), // const widgetconst Text('Click the button to change the state'), // const widgetconst SizedBox(height: 20), // const widgetElevatedButton(key: UniqueKey(), // unique keyonPressed: () {setState(() {_isSelected = !_isSelected;});},child: const Text('Toggle State'),),const SizedBox(height: 20), // const widgetAnimatedBuilder(animation: _isSelected? const AlwaysStoppedAnimation(1): const AlwaysStoppedAnimation(0),builder: (context, child) {return Opacity(opacity: _isSelected ? 1 : 0, // shouldRebuildchild: 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.