Search code examples
flutterdartimmutability

mark class as immutable causes any effects?


Is there any effect of marking a class as immutable? performance... while the codes are running, or while they are compiled? 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;
}

Solution

  • @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!