Home > Enterprise >  mark class as immutable causes any effects?
mark class as immutable causes any effects?

Time:10-15

is there any effect of marking a class as immutable? performance... while the codes are running, or while they are compile ? or is it just for the person reading the code to say "yes, this is a class immutable".

import 'package:flutter/foundation.dart' show immutable;

typedef CloseLoadingScreen = bool Function();
typedef UpdateLoadingScreen = bool Function(String text);

class LoadingScreenController {
  const LoadingScreenController({
    required this.close,
    required this.update,
  });
  final CloseLoadingScreen close;
  final UpdateLoadingScreen update;
}

immutable

import 'package:flutter/foundation.dart' show immutable;


typedef CloseLoadingScreen = bool Function();
typedef UpdateLoadingScreen = bool Function(String text);

@immutable
class LoadingScreenController {
  const LoadingScreenController({
    required this.close,
    required this.update,
  });
  final CloseLoadingScreen close;
  final UpdateLoadingScreen update;
}

CodePudding user response:

@immutable annotation says that a class and all subtypes of that class must be final.

Otherwise, Dart compiler will throw a warning, but not an error.

That's not for other purposes but for tools like dart analyzer to give a warning for you to produce a cleaner, more readable code. There are many places where a Flutter application can make use of immutable structures to improve readability or performance. Lots of framework classes have been written to allow them to be constructed in an immutable form. You can almost totally use immutable classes with state management libraries such as GetX, BLOC, etc.

Neither you wanna declare all class variables final nor get the This class inherits from a class marked as @immutable, and therefore should be immutable (all instance fields must be final). dart(must_be_immutable) warning, you can simple ignore it by using this comment //ignore: must_be_immutable before the class declaration. Have fun!

CodePudding user response:

As from the meta package to which the immutable annotation belongs, the annotations have only an effect on the code reading, dart analyzer.

The library in meta.dart defines annotations that can be used by static analysis tools to provide a more complete analysis of the code that uses them. Within the SDK, these tools include the command-line analyzer (dart analyze) and the analysis server that is used to power many of the Dart-enabled development tools.

So there is nothing to worry about, and you should expect no side effects on your flutter project. in fact, it's used inside the flutter package itself, as an example, the StatelessWidget inherits from the Widget class which is immutable:

  @immutable
  abstract class Widget extends DiagnosticableTree {
  /// Initializes [key] for subclasses.
  const Widget({this.key});
  // more code
   }
  • Related