52

I have an application where you need to log in to continue (for example with Google).

I would like to redirect the user when the authentification is needed.

However when I run a Navigator.of(context).pushNamed("myroute"). I got the following error:

 ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 5624): The following assertion was thrown building _ModalScopeStatus(active):
I/flutter ( 5624): setState() or markNeedsBuild() called during build.
I/flutter ( 5624): This Overlay widget cannot be marked as needing to build because the framework is already in the
I/flutter ( 5624): process of building widgets. A widget can be marked as needing to be built during the build phase
I/flutter ( 5624): only if one of its ancestors is currently building. This exception is allowed because the framework
I/flutter ( 5624): builds parent widgets before children, which means a dirty descendant will always be built.
I/flutter ( 5624): Otherwise, the framework might not visit this widget during this build phase.

Here is a sample code

void main() {
    runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
      routes: <String, WidgetBuilder> {
        "login" : (BuildContext context) => new LoginPage(),
      }
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  int _counter = 0;

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

      if(!isLoggedIn) {
        print("not logged in, going to login page");
        Navigator.of(context).pushNamed("login");
      }

    }


  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  void test() {
    print("hello");
  }

  @override
  Widget build(BuildContext context) {

    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Center(
        child: new Text(
          'Button tapped $_counter time${ _counter == 1 ? '' : 's' }.',
        ),
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: new Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

}

class LoginPage extends StatefulWidget {
  LoginPage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _LoginPageState createState() => new _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  @override
  Widget build(BuildContext context) {
    print("building login page");
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Sign up / Log In"),
      ),
      ),
    );
  }
}

I guess I am doing something wrong, maybe aborting a widget build is causing this. However,, how can I achieve this.

Basically : "I go on my page, if not logged, go to Login page"

Thanks, Alexi

4 Answers 4

88

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.

5
  • 8
    Your second alternative seems way better than the first one. I used this one. Thanks Collin, very useful answer (as always) May 31, 2017 at 6:38
  • 1
    I have a problem in the first solution the context is undefined
    – temirbek
    Mar 17, 2019 at 3:13
  • 1
    where do u add that schulderbinding? ty Jun 29, 2020 at 21:57
  • Where are you guys getting the context from??????? it is undefined
    – b.john
    Jun 30, 2020 at 13:53
  • @b.john widget's State have a context instance property, you're probably trying to call it in a stateless widget or in any other class that is not a State<T>. Also, I recommend to call it inside the initState method, as I'm not quite sure of all the possible side-effects when calling it inside a build method. Sep 14, 2020 at 17:11
23

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');
    });
    
3
  • 1
    undefined name "Timer". Where are you importing it from?
    – Paktalin
    Oct 29, 2020 at 13:09
  • 2
    @Paktalin import dart:async;
    – CopsOnRoad
    Oct 29, 2020 at 15:04
  • Future doesn't work to me. Timer.run works fine!
    – Mark Choi
    Nov 11, 2021 at 14:10
4

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 :)

2

You can also do:

scheduleMicrotask(() => Navigator.of(context).push(MaterialPageRoute(builder: (context) => YourComponent())));
1
  • This code works for me, this is sample from my code Navigator.of(context).push(MaterialPageRoute(builder: ((context) => const Home()))); Jun 24, 2022 at 0:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.