I have two stateful classes and I want to trigger the function triggerFunction() from one class in second class’s build method with onPressed event of a button. Here are the both classes:
import 'package:flutter/material.dart';
class TriggerClass extends StatefulWidget {
const TriggerClass({Key? key}) : super(key: key);
@override
State<TriggerClass> createState() => _TriggerClassState();
}
class _TriggerClassState extends State<TriggerClass> {
void triggerFunction(){}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(),
);
}
}
The Second class:
import 'package:flutter/material.dart';
class UIClass extends StatefulWidget {
const UIClass({Key? key}) : super(key: key);
@override
State<UIClass> createState() => _UIClassState();
}
class _UIClassState extends State<UIClass> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () {
// Here I want to call triggerFunction()
},
child: const Text('Trigger Function'),
),
),
);
}
}
If I use simple class without state, it does call the function but when using stateful, it doesn’t.
>Solution :
Try below code hope its help to you remove _ from TriggerClassState()
Your Trigger Class included with Function
class TriggerClass extends StatefulWidget {
const TriggerClass({Key? key}) : super(key: key);
@override
State<TriggerClass> createState() => TriggerClassState();
}
class TriggerClassState extends State<TriggerClass> {
void triggerFunction() {
print('Button Pressed');
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(),
);
}
}
Your UIClass Widget call your triggerFunction
class UIClass extends StatefulWidget {
const UIClass({Key? key}) : super(key: key);
@override
State<UIClass> createState() => _UIClassState();
}
class _UIClassState extends State<UIClass> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () {
// Here I want to call triggerFunction()
TriggerClassState().triggerFunction();
},
child: const Text('Trigger Function'),
),
),
);
}
}