Home > Enterprise >  Flutter: Calling Function from another Class State
Flutter: Calling Function from another Class State

Time:01-02

My app allows people to post text and switch between different pages on a navbar. On the users page, there is a button, when clicked, will show an overlay so the user can create a post. The overlay includes a back button that calls a function to close the overlay. I want to keep the navbar available at the bottom so user can back out of the post that way if they want to.

The problem is, when the user uses the navbar, the overlay does not close because the close overlay function is on the user page and the navbar page does not have access to it. How do I give another class on another dart file access to a method or function? If you are able to answer, can you please use my code instead of another example to help me follow better? Thank you.

User Page File #1

class UserPage extends StatefulWidget {
  @override
  _UserPageState createState() => _UserPageState();
}

class _UserPageState extends State<UserPage> {
    OverlayEntry? entry;
    @override
    Widget build(BuildContext context) {
        return Scaffold(
            ElevatedButton(
                child: const Text('New Post'),
                    onPressed: showOverlay,
            ),
        ),
    }
    void showOverlay() {
        (...)
    }
    void closeOverlay() {
        entry?.remove();
        entry = null;
    }
}

Nav Bar File #2 (Need help with "OnTap")

class Nav extends StatefulWidget {
  const Nav({Key? key}) : super(key: key);
  @override
  _NavState createState() => _NavState();
}
class _NavState extends State<Nav> {
  int currentTab = 1;  // makes the home page the default when loading up the app
  @override
  void initState() {
    super.initState();
}

List<Widget> tabs = <Widget>[
    const Other(),
    const Home(),
    const UserPage(),
];

@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: tabs.elementAt(currentTab),
      ),

      // BOTTOM NAVIGATION BAR
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: currentTab,
        onTap: (value) {
          setState(() => currentTab = value);
          const _UserPageState().closeOverlay();  //HERE IS WHERE I NEED HELP WITH THE CODE
        },
        items: const [
          BottomNavigationBarItem(
            label: 'Other',
          ),
          BottomNavigationBarItem(
            label: 'Home',
          ),
          BottomNavigationBarItem(
            label: 'User Page',
          ),
        ],
      ),
    );
  }
}

CodePudding user response:

You can try to make your _UserPageState public by removing - from it, and then call it UserPageState().closeOverlay();

  • Related