Why does this error occur: The instance member '*' can't be accessed in an initializer."?

5,863

As you are inside an object and not in a method the attributes _numberOfTeams and _teamPoints can't rely on other attributes to be created because they might not be initialized yet. See the following example, yes it's a little silly but is the same situation for the compiler, it can't guarantee that one is created before the other.

  List<int> _teamPoints = List.filled(_numberOfTeams, 0);
  int _numberOfTeams = _teamPoints.length;

Workarounds

  1. Make the attribute static

Make the dependant value static:

static int _numberOfTeams = 4;
  1. If inside a class you could use an initializer list
class TeamList {
  int _numberOfTeams;
  List<int> _teamPoints;

  TeamList(
    this._numberOfTeams,
  ) : _teamPoints = List.filled(_numberOfTeams, 0);
}
  1. If inside State you could @override initState
class _HomeState extends State<Home> {
  int _numberOfTeams = 4;

  late List<int> _teamPoints;

  @override
  void initState() {
    super.initState();
    _teamPoints = List.filled(_numberOfTeams, 0)
  }

I would prefer approaches 2 or 3 because they are still instances of your objects internal state, you just defer a little bit its creation.

There is more info in dart.dev

Share:
5,863
uuuk
Author by

uuuk

Student

Updated on December 29, 2022

Comments

  • uuuk
    uuuk over 1 year

    I come from a python-background trying to learn java-like languages. This is written in dart for use with flutter.

    I get an error when I try to run the following.

    class _MyGameState extends State<MyGame> {
      int _numberOfTeams = 4;
    
      List<int> _teamPoints = List.filled(_numberOfTeams, 0);
    

    The error message I get is:

    The instance member '_numberOfTeams' can't be accessed in an initializer. Try replacing the reference to the instance member with a different expression

    Why is that, and how does one avoid it? (Obviously, this example is simplified and i could easily simply omit the variable _numberOfTeams and circumvent the problem, but that's not the point.)

    (There are a lot of very similiar questions on here. All the answers to those questions offers ways to cicrumvent the specific problem, but not "why" the problem occurs or how to think when writing in languages where this is common. A few relevant search words that I could look into, or a link to a guide/tutorial/article would be very appreciated :)