Flutter Redirect to a page on initState
Override initState()
funtion and use any of the following:
Future
:Future(() { Navigator.of(context).pushNamed('login'); });
Timer
:Timer.run(() { // import 'dart:async: Navigator.of(context).pushNamed('login'); });
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.
You can also do:
scheduleMicrotask(() => Navigator.of(context).push(MaterialPageRoute(builder: (context) => YourComponent())));
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 :)