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

210 views Asked by At

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?

2

There are 2 answers

4
Ravindra S. Patil On BEST ANSWER

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(),
    );
  }
}
0
JediBurrell On

You need access to the instance of State in order to call one of its functions. Without knowing your use-case, you could create a controller class.

class CounterController {
  late Function increment();
  late Function decrement();
}

Then pass it as a parameter to your Widget.

class CounterWidget extends StatefulWidget {
  final CounterController? controller;
  CounterWidget({this.controller});
}

Then assign the functions in the initState.

class CounterWidgetState extends State<CounterWidget> {
  int count = 0;

  @override
  void initState() {
    widget.controller?.increment = increment;
    widget.controller?.decrement = decrement;
  }

  void increment() {
    setState(() => count++);
  }

  void decrement() {
    setState(() => count--);
  }
}

Then finally you can call the functions.

Row(
  children: [
    CounterWidget(controller: counterController),
    TextButton(
      child: const Text('+'),
      onPressed: () => counterController.increment(),
    ),
    TextButton(
      child: const Text('-'),
      onPressed: () => counterController.decrement(),
    ),
  ]
)