skip to Main Content

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


  1. It doesn´t matter if your Widget is going to be Stateful or Stateless.

    A constant constructor is a constructor which initializes all its
    final fields, and it is often denoted with a const in front of the
    constructor

    So, even if inside the class the values would change (…):

    The const keyword is used when the value of the variable is known at compile-time and never changes. In other words, the compiler knows in advance what value is to be stored in that variable.

    (…) 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.

    Login or Signup to reply.
  2. 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.

    linter:
      rules:
        prefer_const_constructors : false
        # avoid_print: false  # Uncomment to disable the `avoid_print` rule
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search