0

I want to call functions with my classes constructor arguments before passing them to the super method.

Here is a simplified version of my code:

class CustomScaffold extends Scaffold {
  @override
  final Widget body;

  const CustomScaffold({required this.body, Key? key})
      : super(key: key, body: _buildBody());  // <--- it doesnt like this

  Widget _buildBody() {
    return Center(child: body);
  }
}

This is the error that I am getting from AndroidStudio:

error: The instance member '_buildBody' can't be accessed in an initializer. (implicit_this_reference_in_initializer at [bordns_client] lib/ui/base.dart:11)

What is are the best practices for this sort of thing?

1 Answers1

1

You cannot call an instance method from an initializer list (nor before all base class constructors have been executed) because that would allow an instance method to be called before the object has been initialized; this is not valid yet. (Also see: https://stackoverflow.com/a/63319094/)

In your case, you could make your method a static method or a freestanding function that takes body as an argument (or if you don't use _buildBody anywhere else, just pass Center(child: body) directly).

jamesdlin
  • 81,374
  • 13
  • 159
  • 204