简体   繁体   中英

Call setState() method of class from a button click of other class in Flutter

I have a drawer in my main page that changes the body of the scaffold according to selected drawer item, now I need to change the body by tapping on a button in a fragment and call the setState() method of main class with a parameter to update the screen. How can I do this?
this is my Scaffold body:

body: _getDrawerItemWidget(_selectedDrawerIndex));

and when a drawer item is selected the setState() is called and body is filled according to this code :

_getDrawerItemWidget(int pos) {
    switch (pos) {
      case 0:
        return new MainFragment();
      case 1:
        return new CardMgmt();
.........
}
}

but now I need to do this from a button in CardMgmt class.

let me give a super simple approach I use whenever I want to change the state of another class/widget:

define a global variable, then use this variable in the State class of the widget you want to change later. Then you can modify the value of this variable from any method inside your code and state of your first class will change automatically without any direct call of the class' setState() method.

here's an example:

int counter = 0 ;

class _AppState extends State<App> {

var numberOfItems = counter ;

return new MaterialApp(
  title: 'Ads App',
  home: new Text(counter),
 );
}

if you change the value of counter from anywhere from your code the Text widget content will change automatically.

You can make it with callback function.

In parent Widget you creating child Widget and pass callback as parameter:

...
@override
Widget build(BuildContext context) {
  return LoginPage(onSignedIn: _signedIn);
}

void _signedIn() {
  setState(() {
  });
}

In child widget you call this callback, when you need it:

...    
class LoginPage extends StatefulWidget {
  LoginPage({this.onSignedIn});
  final VoidCallback onSignedIn;

  State<StatefulWidget> createState() => new _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
...
void callCallbackFunction() {
  widget.onSignedIn();
}
...

Hope it helps. Good Luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM