StackOverflower
StackOverflower

Reputation: 5761

How to navigate in flutter during widget build?

I'm trying to detect that user is no longer authenticated and redirect user to login. This is how I'm doing it

  Widget build(BuildContext context) {
    return FutureBuilder(
        future: _getData(context),
        builder: (context, snapshot) {
          try {
            if (snapshot.hasError && _isAuthenticationError(snapshot.error)) {
                Navigator.push(context, MaterialPageRoute(builder: (context) => LoginView()));
            }

Unfortunately doing navigation on build is not working. It throws this error

flutter: setState() or markNeedsBuild() called during build.
flutter: This Overlay widget cannot be marked as needing to build because the framework is already in the
flutter: process of building widgets.  A widget can be marked as needing to be built during the build 

I cannot just return LoginView widget since parent widget containts app bar and floating button and login view needs to be displayed without these controlls.. I need to navigate.

Is it possible to do it?

Upvotes: 24

Views: 9228

Answers (3)

DomingoMG
DomingoMG

Reputation: 1857

Streams in flutter

The usual thing is to use a flow where user changes occur. When the user logs off, he detects that change and can direct it to another window.

Upvotes: 0

vinay vishnu
vinay vishnu

Reputation: 59

problem here :

snapshot.hasError && _isAuthenticationError(snapshot.error)

Instead of this use OR

snapshot.hasError || _isAuthenticationError(snapshot.error)

Upvotes: -3

Abion47
Abion47

Reputation: 24661

Wrap it in Future.microtask. This will schedule it to happen on the next async task cycle (i.e. after build is complete).

Future.microtask(() => Navigator.push(
  context, 
  MaterialPageRoute(builder: (context) => LoginView())
));

Upvotes: 57

Related Questions