hpinzon15
hpinzon15

Reputation: 11

Passing data to a State from his Statefulwidget

this is my code and i want to access to "initialValue" propierty from the StatefulWudget but for some reason marks a error in counter = widget.initialValue the image with the error from vs code. I'm following a course and i don't know if something change in the new versions, cause all the questions that i found use the same code.

class MyCounter extends StatefulWidget{


 final int initialValue;

  const MyCounter({Key? key, this.initialValue = 0}) : super(key: key);
  @override
  State createState(){ //puede ser lamda => MyCounterState();
    return MycounterState();
  }
}

class MycounterState extends State{

  int counter = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    counter = widget.initialValue;
  }
...

Or do i have an error in a different part of the code?

Upvotes: -2

Views: 50

Answers (1)

hpinzon15
hpinzon15

Reputation: 11

for someone with the same problem the solution(found in the discord offical flutter server) was "Your state must have a type argument containing the widget"

class MyCounter extends StatefulWidget{
  final int initialValue;

  const MyCounter({Key? key, this.initialValue = 0}) : super(key: key);
  @override
  State<MyCounter> createState(){ //puede ser lamda => MyCounterState();
    return MycounterState();
  }
}

class MycounterState extends State<MyCounter>{

  int counter = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    counter = widget.initialValue;
  }

just need to change State to State<MyCounter> in the "createState()" from MyCounter class and the "extends State{" from MyCounterState class

Upvotes: 0

Related Questions