0

So I've got a bunch of these setting checkboxes that look like this :

SettingsCheckBox(
  value: userSettings.usDateFormat,
  onTap: () => userSettings.usDateFormat = !userSettings.usDateFormat,
  label: 'US Date format',
),

But of course, this is highly repetitive and error-prone code. How can I make this better ? Dart doesn't have pointers as far as I'm aware. I could have a getter/setter on userSettings taking constants corresponding to each boolean so that all the repetitive code is in one place, but that's just really moving the problem away and making things more complex in favor of readability that would be like :

SettingsCheckBox(
  value: SettingsValues.usDateFormatConst,
  label: 'US Date format',
),

With SettingsCheckBox handling the getting/setting of values into userSettings.

ouai
  • 150
  • 1
  • 10

1 Answers1

0

You can add your own level of indirection:

class Reference<T> {
  T value;

  Reference(this.value);
}

SettingsCheckBox makeSettingsCheckBox(Reference<bool> setting, String label) =>
  SettingsCheckBox(
    value: setting.value,
    onTap: () => setting.value = !setting.value;
    label: label,
  );

(Or if SettingsCheckBox is a class that you control, you could make it accept a Reference<bool> directly.)

jamesdlin
  • 81,374
  • 13
  • 159
  • 204
  • This doesn't solve the problem as far as I'm aware, since when I create an instance of Reference, the boolean will by passed-by-value, not by reference. The original value in userSettings won't get updated. – ouai May 19 '23 at 10:10
  • @ouai Sorry, I wasn't clear. My point is that you need to replace `bool`s that you want to mutate into `Reference` objects instead. That is, you would need to change `userSettings` (whatever that is) to use `Reference` members instead of `bool` members. – jamesdlin May 19 '23 at 15:22
  • Yes, but complexifying code like this is for readability exactly what I'm trying to avoid. I actually already have a class exactly like this that I use to keep type safety across Navigator calls (instead of using values returned by Navigator.pop). – ouai May 19 '23 at 18:12
  • @ouai The point is to reduce the likelihood of errors by ensuring that the same member name is used everywhere. Yes, readability is harmed slightly by needing to add `.value` in some places, but that is pretty minor. This is the best you can do; Dart does not expose raw pointers or mutable `bool` objects. – jamesdlin May 19 '23 at 18:23