10
votes

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?

3
How do users log in? Is it by firebase? - DomingoMG

3 Answers

21
votes

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())
));
0
votes

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.

Here I attach more information than I try to explain:
https://codingwithjoe.com/flutter-authentication/

-2
votes

problem here :

snapshot.hasError && _isAuthenticationError(snapshot.error)

Instead of this use OR

snapshot.hasError || _isAuthenticationError(snapshot.error)