Dart/Flutter: How to print something into the console from constructor

318

You have to open a block body after the constructor and print it there.

void main() {
  Dog myDog = Dog();
}

class Dog {
  Dog() {
    print('woof');
  } 
}

Your case:

class MyClass extends StatefulWidget {
  MyClass({this.test}) {
    print(a);
  }
  int a = 77;

  @override
  _MyClassState createState() =>
      _MyClassState();
}
…
Share:
318
BNetz
Author by

BNetz

Updated on December 12, 2022

Comments

  • BNetz
    BNetz over 1 year

    I want to print something to the console from my constructor as shown in the snippet below, but I get the error

    Context: 'SeitenzahlenrechnerErgebnis.print' is defined here.
      print(a);
    

    How/where can I execute the print(a)?

    class MyClass extends StatefulWidget {
      MyClass({this.test});
      int a = 77;
      // I would like to say
      // print(a);
      // here, but no way …
    
      @override
      _MyClassState createState() =>
          _MyClassState();
    }
    …
    

    I am new to Flutter/Dart - would appreciate help a lot. Thanks!

  • BNetz
    BNetz about 3 years
    Thanks, but I don't understand how to use this in my example above.
  • pedro pimont
    pedro pimont about 3 years
    @BNetz try it now
  • BNetz
    BNetz about 3 years
    I see - this is the behavior I wanted, thanks a lot!