0

I would like a member of a class to received a listner from its owner class. So, something like this:

class Member {
  Member({required this.listener});
  final VoidCallback listener;
}

class Owner {
  final member = Member(listener: saySomething); // <- error here

  void saySomething() {
    debugPrint('hello');
  }
}

But I get the error on listener: saySomething that reads instance member can't be accessed in an initializer. My understanding is that it's because the compiler builds the Member instance first and then the Owner instance, so doesn't have the locations in memory yet.

I know I can do this in two steps. E.g., instantiate member and then assign its listener in my constructor or wherever, but it would be really nice if I could assign listener when member is instantiated.

I'm pretty sure that's not possible but am hoping to be proven wrong?

buttonsrtoys
  • 2,359
  • 3
  • 32
  • 52
  • Ah. The "already answered" link discusses using the late keyword to lazy initialize. I didn't know you can do that in a single line of code. That's pretty sweet. So, I can `late final member = Member(listener: saySomething);` – buttonsrtoys Aug 11 '22 at 18:30

1 Answers1

0

You can either pass the function directly into the constructor, or you can make saySomething into a static method, rather than an instance method:

// Directly passing the function
class Owner {
  final member = Member(listener: () {
    debugPrint('hello');
  });
}

// Using a static method
class Owner {
  final member = Member(listener: saySomething);

  static void saySomething() {
    debugPrint('hello');
  }
}
Michael Horn
  • 3,819
  • 9
  • 22
  • Thanks. My example was too simplistic. My actual listener can't be static. It references other Owner members. For that reason, I don't think the first option will work either because the other members would need to be in the closure. – buttonsrtoys Aug 11 '22 at 18:13
  • 1
    I read the "already answered" like above and it describes how I can late initialize. So, `late final member = Member(listener: saySomething);` which is pretty sweet. – buttonsrtoys Aug 11 '22 at 18:37