So i have this toggle()
method in the Stateful SideBar
class
class SideBar extends StatefulWidget {
const SideBar({super.key});
@override
State<SideBar> createState() => _SideBarState();
}
class _SideBarState extends State<SideBar> with SingleTickerProviderStateMixin{
void toggle() {
if (_controller.isCompleted) {
_controller.reverse();
}
else {_controller.forward();}
}
}
and i want to use it in
class SideBarWidget extends StatelessWidget {
SideBarWidget({Key? key}) : super(key: key);
final SideBar sideBarWidget = SideBar(...);
void toggle() {
// here i want to use the toggle() method
}
@override
Widget build(BuildContext context) {
return sideBarWidget;
}
}
I cannot use sideBarWidget.toggle()
I also cannot pass it as a parameter becasue the _controller is in the SideBar()
widget
3
Answers
There are many ways, but the most common and simple is to create an instance of the
SideBar
class inside theSideBarWidget
class, for example:And then you can access the
toggle()
method like this:side.toggle()
.One way is to give the
SideBar
aGlobalKey
and get the state from the key afterwards. An example: