Home > Software design >  Flutter - How to call functions (and variables) between stateful widgets?
Flutter - How to call functions (and variables) between stateful widgets?

Time:10-13

I have this function in a widget (homescreen):

    void toggleRecording() async {

  //HERE IS THE CONFUSION I GUESS
  _isRecording = !_isRecording;
  recorder = SoundStream(isRecording: _isRecording);

  //recorder.toggleRecording(_isRecording);
  setState(() {
    _isRecording = recorder.isRecording;
  });
  if (_isRecording) {
    startTimer();
    _stopwatch.start();
  } else {
    stopTimer();
    _stopwatch.stop();
  }
}

It needs to call (trigger) another function in my recorder class:

void toggleRecording() async {

  widget.isRecording  ////// currently being passed as an arguement from homescreen

      ? {_recorder.stop, await save(_micChunks, 44100)}
      : _recorder.start;
}

Also, the boolean variable _isRecording is present in both the classes. How do I sync the state?

CodePudding user response:

In your situation passing reference of function through widgets will work. However best practice of this will be using

At provider folder we define our provider classes.

Firstly i define class which extends changeNotifier class. This is what make this class provider.

Side note: notifyListener() function here calls setState of every widget if you use any variables inside that class and this is what you are searching for.

Then i import it into my main.dart file or whatever file you want. Only condition is being above the widget that you will use provider at.

At last you can use your function at everywhere if you import provider package and define your provider like i did in this code.

At last here is the visualized stucture of provider package.

I wish i explained it well. There is more about it on youtube.

CodePudding user response:

Pass the function to other widget 
using Function keyword


Say ContentWidget is your child and ParentWidget is parent

class ParentWidget extends StatefulWidget {

//Do Something
void onSomeFunction()
{
ContentWidget(onTimerUpdate:onTimerClosed)

}

void onTimerClosed()
{
//Perform Operation on Timer Change
}



}

class ContentWidget extends StatefulWidget {
 final Function onTimerUpdate;

ContentWidget({
 Key key,
 @required this.onTimerUpdate,
  }) : super(key: key);

void onAnyActionFromChild()
{
widget.onTimerUpdate() //Note () can have any param or can be null
}
  • Related