Dart, Only static members can be accessed in initi

2019-08-28 12:35发布

问题:

In this code below,

class SimpleClass {
  final String ID;

  BusInformationScreen({this.ID});

  var output = ID;
}

I got an error Only static members can be accessed in initializers.

so i adjusted code like this below.

class SimpleClass {
  static final String ID;

  var output = ID;
}

I thought if i declare ID as a static, It doesn't have to initialize it but i got an error like this.

The final variable 'ID' must be initialized.

What is the reason that i couldn't declare variable output?


class SimpleClass {
  final String ID;
  final String output;
  SimpleClass_2 simpleclass_2 = SimpleClass_2(parameter: ID), SimpleClass_2 simpleclass_2 = SimpleClass_2(parameter: ID);

  SimpleClass({this.ID}): output = ID;
}

class SimpleClass_2 {
  final parameter;

  SimpleClass_2({
    this.parameter
  });
}

回答1:

(I'm gonna assume BusInformationScreen is supposed to be the constructor for SimpleClass )

The problem is

var output = ID;

You're trying to set the value for output before the class has been constructed. You can set it in the initializer list instead :

  SimpleClass({this.ID}):
        output= ID;


标签: dart