Atamyrat Babayev
Atamyrat Babayev

Reputation: 890

Flutter Provider with Navigation

Currently I have a provider with 3 state Response (Success, Error, Running) and consumer which listening to this provider. Is it possible to push to another route, when response from provider is Success? Here is my consumer:

class SplashScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: _splashWidget(context),
    );
  }

  Widget _splashWidget(BuildContext context) {
    return Consumer<AccessTokenProvider>(builder: (context, myModel, child) {
      switch (myModel.accessToken.status) {
        case Status.COMPLETED:
        Navigator.of(context).pushReplacementNamed(MainRoute);
        return null;

        case Status.ERROR:
        return ErrorScreen();

        default:
          return SplashProcessing();
      }
    }, );
  }
}

Is it a good case to make navigation in this way? Thanks!

Upvotes: 3

Views: 2333

Answers (2)

Lab
Lab

Reputation: 1397

Widget _splashWidget(BuildContext context) {
    return Consumer<AccessTokenProvider>(builder: (context, myModel, child) {
      switch (myModel.accessToken.status) {
        case Status.COMPLETED:
        WidgetsBinding.instance.addPostFrameCallback((_) => 
           Navigator.of(context).pushReplacementNamed(MainRoute)); // can also use: Future.microtask(() => Navigator.of(context). pushReplacementNamed... );
        return Container(); // always return a widget in the build method, not null

        case Status.ERROR:
        return ErrorScreen();

        default:
          return SplashProcessing();
      }
    }, );
  }

Upvotes: 1

Lab
Lab

Reputation: 1397

Your widget should not return null (Status.COMPLETED). So if you want to use the navigator AND show widgets depending the state of your consumer, you should add a listener who will push to the MainRoute, and a builder (like your consumer here) to show the ErrorScreen or SplashProcessing.

Upvotes: 0

Related Questions