Home > database >  How to access the final parent StatefulWidget class variables from its extended class?
How to access the final parent StatefulWidget class variables from its extended class?

Time:11-25

I've ExperienceCardFront a StatefulWidget class which extends _ExperienceCardFrontState.

I'm trying to access the variables (marked as final and required) in ExperienceCardFront from its state, _ExperienceCardFrontState.

This is my ExperienceCardFront:

class ExperienceCardFront extends StatefulWidget {
  const ExperienceCardFront(
      {Key? key, required this.title, required this.image})
      : super(key: key);

  //the 2 variables I want to get access to from the extended class
  final String title;
  final String image;

  @override
  _ExperienceCardFrontState createState() => _ExperienceCardFrontState();
}

And this is my _ExperienceCardFrontState:

class _ExperienceCardFrontState extends State<ExperienceCardFront> {
  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }
  
  @override
  Widget build(BuildContext context) {
    return Container(
       //here I want to get access to the title (or image) variable from ExperienceCardFront
       child: Text(title),
    );
  }

}

The following error is thrown: Undefined name 'title', when I try to run this code.

CodePudding user response:

**Try this **

class _ExperienceCardFrontState extends State<ExperienceCardFront> {
  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }
  
  @override
  Widget build(BuildContext context) {
    return Container(
       //here I want to get access to the title (or image) variable from ExperienceCardFront
       child: Text(widget.title),
    );
  }

}

CodePudding user response:

You can just call widget.title

@override
      Widget build(BuildContext context) {
        return Container(
           //here I want to get access to the title (or image) variable from ExperienceCardFront
           child: Text(widget.title),
        );
      }
  • Related