Search code examples
flutterdartcallbackstate

How to Trigger Callbacks on Flutter Bottom Navigation Bar Page Changes with Stateful Pages: Implementing Callbacks Between Two Classes


I have a flutter application with a bottom navigation bar that keeps page states in the navigation (I use go_router). I've been trying for a long time to get a callback on my fav page as soon as I arrive on the page. But I can't, so here's an outline of what I'd like:

Page 1 (which manages navigation):

void _tabChanged() {
   ...
}
...
LazyIndexedStack(
              index: _controller.index,
              children: const [
                Home(),
                Fav(), // it should be sent the callback, linked with tabChanged()
              ],
            ),

And for the page, you'd have to receive the callback:

const Fav({Key? key, required this.callback}) : super(key: key);
...
widget.callback() {
... here I receive the callback from tab.dart
}

Solution

  • Thank you very much PurplePolyhedron, I received an error so here's how I did it in the end:

    GlobalKey<FavState> key = GlobalKey<FavState>();
    void _handleTabChanged() {
      if (_tabController.index == 1) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (key.currentState != null) {
            key.currentState!.test();
          }
        });
      }
      ...
    }
    ...
    LazyIndexedStack(
      index: _controller.index,
        children: [
          const Home(),
          Fav(
            key: key,
          ),
        ],
    ),
    

    and in the Fav page:

    void test() {
        setState(() {
          ...
        });
      }