Home > Software engineering >  What's the correct way to use methods from a sibling widget?
What's the correct way to use methods from a sibling widget?

Time:07-04

I am trying to clean my code by putting different widgets in different files/classes so it's not all inside the same main widget.

So right now I have this:

MainWidget {
Scaffold {
    body: MyWebView(),
    bottomNavigationBar: MyNavBar(),
}
}

Both are stateful widgets.

So now I'm wondering: how can I use methods from MyWebView from inside MyNavBar?

I've tried MyWebView.of(context).method() and even do a middle method inside MainWidget to try and call the methods from the parent widget always, but it's always "null". I've seen people mentioning PrivateKeys but many say this is an old way of doing things and I shouldn't rely on that.

So how can I do this?

CodePudding user response:

I would need more details to provide an exact solution but based on your question this is the answer: You have two options to do what you need

  1. Lift Up The state: This means In some situations, there are some states that are needed and shared among two or more sibling widgets, what we can do about it is to move those states to the parent widget, and provide it to the children, either by passing the variables and functions or using inherited-widget-based methods like using provider framework. so in your case, you can keep the function and state in the main widget, and pass it to both children.
  2. Use a Key to access the MyWebView widget's state: as you mentioned in the comments, this is exactly done as you said :

you'd have to do it on the MainWidget, pass it onto the MyWebView(key: key), and then pass it to MyNavBar(webviewKey: key) to use it there

CodePudding user response:

if you want to pass variable instead use typedef,

first declare outside MyWebview class : let me guess, you need some int value from webview to pass it into navbar class.

typedef OndataProcessed = void Function(int valueIneed);
class MyWebView {
--------
final OndataProcessed ondataprocess;

and in methods in my webview

int someMethod (){

int result = blabla;

ondataprocess(result);
}

and finally :

MainWidget {
int resultfromwebview;
Scaffold {
    body: MyWebView(ondataprocess: (int result){
setstate((){resultfromwebview = result})
}),
    bottomNavigationBar: MyNavBar(index: result),
}
}
  • Related