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?
Asked
Active
Viewed 156 times
2 Answers
0
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(),
);
}
}

Ravindra S. Patil
- 11,757
- 3
- 13
- 40
-
Thank you buddy, its working but state is not updating in another class, How to do that? – Rakesh Saini Aug 02 '21 at 11:32
-
I cant understand can you explain me in brief and **mobileGraphFunction** inside `MobileGraph` class is Widget – Ravindra S. Patil Aug 02 '21 at 11:35
-
Your code is working perfect, but the method is not updating its state. How to do that? I am calling a method in ProfileUpdate{} class, which is situated in Drawer{} class, i want to update Drawers's UserAccountsDrawerHeader profile photo from ProfileUpdate{}. Method is calling but profile is not updating its state. – Rakesh Saini Aug 02 '21 at 12:00
-
Its Working for me – Ravindra S. Patil Aug 02 '21 at 12:04
0
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(),
),
]
)

JediBurrell
- 1,069
- 10
- 24