简体   繁体   中英

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?

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

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

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.

problem here :

snapshot.hasError && _isAuthenticationError(snapshot.error)

Instead of this use OR

snapshot.hasError || _isAuthenticationError(snapshot.error)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM