Search code examples
dartconstructorconstants

Dart immutable object with immutable list


I am trying to create a class that is immutable, since it is a sort of EventArgs class. I want to know how const and immutable I can make my fields. This is what I have so far:

import 'package:meta/meta.dart';

@immutable
class ConnectedDevicesChangedEventArgs {
  final Iterable<String> devices;

  const ConnectedDevicesChangedEventArgs(Iterable<String> d)
      : devices = const List.unmodifiable(d); // error on const
}

I get an error saying:

The constructor being called isn't a const constructor. Try removing 'const' from the constructor invocation.dartconst_with_non_const

I have the following requirements:

  • Anyone accessing the EventArgs class is not allowed to change devices
  • Anyone accessing the EventArgs class is not allowed to add/remove anything from the devices
  • devices will simply never change

Is it a good practice to make this constructor const, since there is only a final variable?

I have read this: https://dart.dev/guides/language/language-tour#constant-constructors


Solution

  • A final List.unmodifyable() can neither be change to a different list, not have the list itself modified.

    However, it does not satisfy Dart's requirements for a const constructor, which states that the entire instance can be computed at compile time.

    In this case, you can simply omit the const keyword.