anta40
anta40

Reputation: 6743

How to access data from parent widget?

I have this screen which displays user profile:

class DisplayProfile extends StatefulWidget {

  final UserProfile profile; // profile contains name and email

  const DisplayProfile({Key? key, required this.profile}) : super(key: key);

  @override
  _DisplayProfileState createState() {
    return _DisplayProfileState();
  }
}

class _DisplayProfileState extends State<DisplayProfile> {

    Widget profileWidget() {
        return SingleChildScrollView(
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: <
            Widget>[
          Padding(
          padding: EdgeInsets.all(4.0),
          child: Text("Name",
              style: TextStyle(fontWeight: FontWeight.bold))),
          Padding(
          padding: EdgeInsets.all(4.0),
          child: Text(profile.name,
              style: TextStyle(fontWeight: FontWeight.bold))),
          Padding(
          padding: EdgeInsets.all(4.0),
          child: Text("E-mail",
              style: TextStyle(fontWeight: FontWeight.bold))),
          Padding(
          padding: EdgeInsets.all(4.0),
          child: Text(profile.email,
              style: TextStyle(fontWeight: FontWeight.bold))),
        ]));
      }
      
      @override
      Widget build(BuildContext context) {
        return SafeArea(
          top: false,
          child: Scaffold(
          ....
          )
        )
      }
  }

Of course, the code above won't compile. Flutter complains:

The getter 'name' isn't defined for the type '_DisplayProfileState'.

How to make profile in DisplayProfile accessible from _DisplayProfileState?

Upvotes: 2

Views: 140

Answers (1)

Jahidul Islam
Jahidul Islam

Reputation: 12565

Add widget before profile as follows:

 Padding(
          padding: EdgeInsets.all(4.0),
          child: Text(widget.profile.name,
              style: TextStyle(fontWeight: FontWeight.bold))),
          Padding(
          padding: EdgeInsets.all(4.0),
          child: Text("E-mail",
              style: TextStyle(fontWeight: FontWeight.bold))),
          Padding(
          padding: EdgeInsets.all(4.0),
          child: Text(widget.profile.email,
              style: TextStyle(fontWeight: FontWeight.bold))),

Upvotes: 3

Related Questions