Ian Rehwinkel
Ian Rehwinkel

Reputation: 2615

Set State of parent Widget

Let's say, I have a custom button widget and I want to set the state of it's parent using setState. How exactly can I access the parent widget's state from my custom button? Is it even possibile?

Upvotes: 14

Views: 21982

Answers (2)

Mohamed Hussin
Mohamed Hussin

Reputation: 1

// Define global key
static GlobalKey gk= GlobalKey();

// Assign global key in constructor
class mainScreen extends StatefulWidget {
  mainScreen(): super(key: data.gk);

  // Call the setState from parent widget or from any where
  if (gk.currentState != null) {
    data.gk.currentState!.setState(() {

    })
  }
}

Upvotes: 0

Dinesh Balasubramanian
Dinesh Balasubramanian

Reputation: 21758

You can use callbacks functions to achieve this. You can refer here.

In the link

  • FeedPage is similar to CustomButton(ChildWiget)
  • RootPage is similar to ParentWiget

Upvotes: 11

Related Questions