Flutter重定向到initState上的页面

时间:2017-05-30 18:57:23

标签: routes dart flutter

我有一个应用程序,您需要登录才能继续(例如使用Google)。

我想在需要验证时重定向用户。

然而,当我运行Navigator.of(context).pushNamed("myroute")时。我收到以下错误:

 ══╡ 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.

以下是示例代码

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"),
      ),
      ),
    );
  }
}

我想我做错了什么,也许中止小部件构建导致了这个问题。但是,我怎样才能做到这一点。

基本上:&#34;我继续浏览我的页面,如果没有登录,请转到登录页面&#34;

谢谢, 奕利

4 个答案:

答案 0 :(得分:24)

尝试打包Navigator来电:

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

在使用addPostFrameCallback安排的回调中:

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

您需要在文件顶部进行此导入:

import 'package:flutter/scheduler.dart';

作为替代方案,如果用户不是&#39,请考虑是否可以让MyHomePage build()方法返回LoginPage而不是Scaffold ; t登录。由于您不希望用户在登录之前退出登录对话框,因此可能会更好地与后退按钮进行交互。

答案 1 :(得分:1)

另一种方法是在打开需要身份验证的新页面之前 进行登录检查。 主页保留为“欢迎” /信息页面,并且当用户点击菜单项时,将执行登录检查。

已登录:打开新页面。 注销:登录页面已打开。

为我工作:)

答案 2 :(得分:0)

@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");
  });
}

答案 3 :(得分:0)

您也可以这样做:

scheduleMicrotask(() => Navigator.of(context).push(MaterialPageRoute(builder: (context) => YourComponent())));