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?
How to call a function from another statefull class in flutter?
210 views Asked by Rakesh Saini At
2
There are 2 answers
0
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(),
),
]
)
Try below Code hope it helps you:
Declare first stateful class with your function :
then call mobileGraphFunction in other stateful class like as :