Home > Software engineering >  Can I remove const in the below flutter code?
Can I remove const in the below flutter code?

Time:09-27

After updating to flutter 2.5 the const modifier is added to the default code and there are places where const is to be added where we don't have to earlier. so what's the difference between adding a const?

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const HomePage(),
    );
  }
}

CodePudding user response:

This is flutter_lint and it uses by default in flutter. Flutter apps, packages, and plugins created with flutter create starting with Flutter version 2.3.0 are already set up to use the lints defined in this package.

Disabling individual rules

include: package:lints/recommended.yaml

linter:
  rules:
    avoid_shadowing_type_parameters: false
    await_only_futures: true

For more read this analysis option

CodePudding user response:

When you create a widget, and is able to prefix it with const that widget will not rebuild. The framework knows not to rebuild such widgets because it can tell that the objects did not change. Constant objects are resolved at compile time, and due to a process known as canonicalization if two or more objects have the same parameters, and are constant, they will refer to the same instance (They are one and the same).

For example if you have

@override
Widget build() {
  const MyWidget();
}

And then somewhere you call setState, MyWidget will not be reconstructed because it was already resolved at compile time, and the framework will also not call its build method which makes sense because non of the arguments passed to MyWidget (which are none here) have changed as a result of issuing the rebuild so the configuration is still the same.

Moreover if somewhere else you call cosnt MyWidget(); you will still refer to the same object/instance so it's more optimal.

Bottomline is if you are able to prefix with const then you definitely should do so. And they added the lint rule so that people add a cosnt constructor and are able to invoke their widgets/classes with cosnt and take advantage of the stuff mentioned above.

  • Related