Solved: How to use a method in a Stateful Widget from another Widget

Question

Asked by Pulina H on January 24, 2023 (source).

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

Answer

Question answered by Hitarth C (source).

remove underscore from SideBarState

to use method of SideBarState in SideBarWidget use: SideBarState().toggle();

**screen1.dart**

    class ParentWidget extends StatefulWidget {
              const ParentWidget({Key? key}) : super(key: key);
            
         
    
     @override
          State<ParentWidget> createState() => ParentWidgetState();
        }
        
    class ParentWidgetState extends State<ParentWidget> {
      
      void printData() {
        print("parent");
      }
    
      @override
      Widget build(BuildContext context) {
        return const Placeholder();
      }
    }

**screen2.dart**

    import 'package:demo/screen_1.dart';
    import 'package:flutter/material.dart';
    
    class ChildWidget extends StatelessWidget {
      const ChildWidget({Key? key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        ParentWidgetState().printData();
        return const Placeholder();
      }
    }

Video Answers on YouTube

DART FLUTTER METHODS STATEFULWIDGET STATELESSWIDGET
SHARE: