Flutter is highlighting my Login()
below with a yellow line telling me that the const
keyword should be used to improve performance. But my Login
widget is a stateful widget, whose state can change. What is is about my Login
widget that makes it appropriate to add the const
keyword here?
wrapper.dart:
class Wrapper extends StatelessWidget {
const Wrapper({super.key});
@override
Widget build(BuildContext context) {
return Consumer<GlobalsProvider>(builder: (context, value, child) {
return Login(); //Warning points here, telling me to change the line to 'return const Login();'
});
}
}
login.dart:
class Login extends StatefulWidget {
const Login({super.key});
@override
State<Login> createState() => _LoginState();
}
class _LoginState extends State<Login> {
...
}
2
Answers
It doesn´t matter if your Widget is going to be Stateful or Stateless.
So, even if inside the class the values would change (…):
(…) The final attributes inside the class remains the same (in this case just the
super.key
one).Long story short:
By making a widget
const
, you can prevent it from being rebuilt when its parent is rebuilt, assuming its properties remain the same. This optimization improves performance by building the widget only once.It will prevent the Widget from being rebuild when its parent is rebuilt, as you already know that it will not change ever. Thus, only needing to build it once, you gain performance by making it a const.
You can also disable const suggestion everywhere (but you shouldn’t because it will help you to improve performance of your app)
To avoid the prefer const with constant constructors warning add this rule prefer_const_constructors : false to the analysis_options.yaml file.