Flutter Redirect to a page on initState

与世无争的帅哥 提交于 2019-11-30 04:49:31

Try wrapping your Navigator call:

Navigator.of(context).pushNamed("login");

in a callback that is scheduled with addPostFrameCallback:

SchedulerBinding.instance.addPostFrameCallback((_) {
  Navigator.of(context).pushNamed("login");
});

You'll need this import at the top of your file:

import 'package:flutter/scheduler.dart';

As an alternative, consider if you could just have MyHomePage's build() method return a LoginPage instead of a Scaffold if the user isn't logged in. That will probably interact better with the back button since you don't want the user backing out of the login dialog before they are done logging in.

Another approach is to perform the login check before a new page, that needs authentication, is opened. The main page is reserved as a "welcome"/info page and when user tap on a menu item the login check is performed.

Logged in: New page is opened. Logged out: Login page is opened.

Works for me :)

@override
void initState() {
  super.initState();

  // it will navigate to login page as soon as this state is built
  Timer.run(() {
    Navigator.of(context).pushNamed("login");
  });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!