flutterdartstatefulwidgetpass-data

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?


Solution

  • 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