How to call a method from a StatefulWidget class to another StatefulWidget class in the flutter

When we create classes in Flutter, sometimes we have to use this method from class to another, so now in this post, we will share this information with you how we can do this.

We can easily pass the method of one class to another class but when two StatefulWidget class is there then we have difficulty in accessing the method but we can send the data from one class to another class through the constructor and if you are working on the mobile application, you can send data from one class to another class from the SharedPreferences.

How to Use StatefulWidget class method in other Class

Now we have a StatefulWidget class to access the method of the second StatefulWidget class, for this we have to create a constructor and call this method on the action of a button in the second class, then we can use the method of our first class.

Example of StatefulWidget Class method



Screenshot of example

Source code of above example

class page1 extends StatefulWidget {
@override
_page1State createState() => _page1State();
}
class _page1State extends State<page1> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Flutter Example"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[

FlatButton(
color: Colors.blue,
onPressed: (){
page2()._callMethod(context);
},
child: Text("Button on Class 1",style: TextStyle(color: Colors.white),),
),
],
),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}


 class page2 extends StatefulWidget {

_callMethod(BuildContext context) => createState().alertBoxMethod(context);
@override
_page2State createState() => _page2State();
}
class _page2State extends State<page2> {
alertBoxMethod(BuildContext context)
{
print("page B");
return showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
content: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Container(
width: 32,
child: Text("Alert Box on Class 2"),
);
},
),
);
}
);
}
@override
Widget build(BuildContext context) {
return Container();
}
}

The method of one StatefulWidget class needs any more information related to the way the method is called in another StatefulWidget or if you have any questions, you can tell us by commenting below.

Previous
Next Post »