Using const widgets helps to avoid unnecessary rebuilds because the widgets are only built once and reused when the state changes.

  1. import 'package:flutter/material.dart';
  2. class MyWidget extends StatefulWidget {
  3. @override
  4. _MyWidgetState createState() => _MyWidgetState();
  5. }
  6. class _MyWidgetState extends State<MyWidget> {
  7. bool _isSelected = false;
  8. @override
  9. Widget build(BuildContext context) {
  10. return Column(
  11. children: [
  12. const SizedBox(height: 20), // const widget
  13. const Text('Click the button to change the state'), // const widget
  14. const SizedBox(height: 20), // const widget
  15. ElevatedButton(
  16. key: UniqueKey(), // unique key
  17. onPressed: () {
  18. setState(() {
  19. _isSelected = !_isSelected;
  20. });
  21. },
  22. child: const Text('Toggle State'),
  23. ),
  24. const SizedBox(height: 20), // const widget
  25. AnimatedBuilder(
  26. animation: _isSelected
  27. ? const AlwaysStoppedAnimation(1)
  28. : const AlwaysStoppedAnimation(0),
  29. builder: (context, child) {
  30. return Opacity(
  31. opacity: _isSelected ? 1 : 0, // shouldRebuild
  32. child: Container(
  33. color: Colors.red,
  34. height: 100,
  35. width: 100,
  36. ),
  37. );
  38. },
  39. ),
  40. ],
  41. );
  42. }
  43. }

With this technique you can help to reduce widget rebuilds in your Flutter app and improve its performance.