Mount common widgets on every screen in a Flutter app

Viewed 730

How do I add a common widget to every screen in a flutter app. I found another answer on StackOverflow but I wouldn't want to add the CommonWidgets page on each page separately. I am looking for a way to declare the common widgets just once.

I am trying to include an Alert Screen which can be accessible across the flutter app and I want the AlertsScreen widget to be state driven (i.e, push values to AlertsScreenState from anywhere then the alerts will popup).

I did something like this:

MaterialApp(
  builder: (BuildContext context, Widget widget) {
    setErrorBuilder();

    return Column(
      children: <Widget>[
        Expanded(
          child: widget,
        ),
        AlertsScreen(),
      ],
    );
  },
  title: 'App name',
  onGenerateRoute: Router.onGenerateRoute,
  initialRoute: Router.splashScreen,
  navigatorKey: Router.navigator.key,
),

It is working fine and even I could make the mobx state management work perfectly fine, but when I try to display any Widget using the context within the AlertsScreen widget it throws me the error:

[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: Navigator operation requested with a context that does not include a Navigator. The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget.

Flush bar example:

Flushbar(
      title: 'title',
      message: 'body',
      duration: const Duration(seconds: 5),
    ).show(context);

The above error is thrown whenever I try to show Flushbar using the context of the AlertsScreen widget. I suspect that this error is thrown because the navigator is currently rendering another Widget of the app and the AlertsScreen isn't been able to access the context correctly.

How do I get it working?

0 Answers
Related