larryq
larryq

Reputation: 16299

Updating a stateful widget variable after it has rendered?

I'm using a TabBarView with two tabs that each display a Stateful widget-- Let's call them the Main Widget and the Configuration Widget.

The Configuration Widget serves as a 'configuration section' for the Main Widget-- I use it to set things like the background color and a URL variable in the Main Widget that's used to grab data from a web service.

The Main Widget has a ListView that is populated by that web service. I'm using the Bloc pattern to send events from one widget to the other, which is how the Configuration Widget sends a URL value over to the Main Widget-- an event is fired, which courtesy of the bloc becomes a 'state' object with the new URL in it that the Main Widget can read in its constructor and use to build the ListView.

Right now I use the wantKeepAlive mechanism in the Main Widget to avoid repopulating the ListView if I haven't changed the URL in the Configuration Widget-- if I don't do so the Main Widget rebuilds whenever I return to its tab, even if I haven't changed anything in the Configuration Widget.

What I want to do is have that value set selectively, so that when the URL is changed in the configuration, update the wantKeepAlive value to false so the ListView does rebuild with the new URL. But when it's done building, set the wantKeepAlive value back to true, so no rebuilding is done, until the next URL change.

Is there a lifecycle method I can call when a build() method is completed, where I can set the wantKeepAlive setting? I don't think doing so in the build method itself would work. Open to suggestions, and thanks.

Upvotes: 0

Views: 701

Answers (1)

diegoveloper
diegoveloper

Reputation: 103421

You can use addPostFrameCallback of your WidgetsBinding instance to execute some code after your widget was built.

  _onLayoutDone(_) {
    //add your code here
  }

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback(_onLayoutDone);
    super.initState();
  }

Upvotes: 2

Related Questions