Home > OS >  How to override State class so I could access StatefulWidget instance?
How to override State class so I could access StatefulWidget instance?

Time:05-30

So I have 2 classes:

class A extends StatefulWidget {
  A({Key? key}) : super(key: key);

  @override
  State<A> createState() => _AState();
}

class _AState extends State<A> {
  @override
  Widget build(BuildContext context) {
    return Container();
  }

  void func(){}
}

And I want to override the _AState classes func() method. So I do this like this:

class B extends A{
  final item = 10;

  @override
  State<A> createState() => _BState();
}

class _BState extends _AState{
  @override
  void func() {
    widget.item //can't do this
  }
}

I have no problem overriding the func() method, but now I also need to access my new variable item, that is declared in B class. And I know I can't do that because instance widget is provided by State<A> class.

So my question is: How to access the variable item from B class in _BState?

CodePudding user response:

Cast the widget to B object

class _BState extends _AState{
  @override
  void func() {
    // (widget as B).item 
  }
}
  • Related