How to call a function from another statefull class in flutter?

Issue

I am learning flutter, I want to call a function (which is in statefull class) into another statefull class. I searched everywhere but there is no solid solution. Can anyone just suggest or provide me the wright way to call the function?

Solution

Try below Code hope it helps you:

Declare first stateful class with your function :

class MobileGraph extends StatefulWidget {
  _MobileGraphState mobileGraph = _MobileGraphState();
  @override
  _MobileGraphState createState() => mobileGraph;
  mobileGraphFunction() {
    mobileGraph.mobileGraphFunction();
  }
}

class _MobileGraphState extends State<MobileGraph> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: mobileGraphFunction(),
    );
  }
}

then call mobileGraphFunction in other stateful class like as :

class Graph extends StatefulWidget {
  @override
  _GraphState createState() => _GraphState();
}

class _GraphState extends State<Graph> {
  MobileGraph mobileGraph;
  @override
  void initState() {
    super.initState();
    mobileGraph = MobileGraph();
  }
@override
  Widget build(BuildContext context) {
    
    return Scaffold(
      appBar: AppBar(
        title: Text(
          'All Graphs',
          style: TextStyle(fontSize: 25),
        ),
        
      ),
      body: mobileGraph(),
    );
  }
}

Answered By – Ravindra S. Patil

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *