Flutter 重定向到 initState 上的页面 [英] Flutter Redirect to a page on initState

查看:25
本文介绍了Flutter 重定向到 initState 上的页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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.

这是一个示例代码

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"

谢谢,亚历克斯

推荐答案

尝试封装您的 Navigator 调用:

Try wrapping your Navigator call:

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

在使用 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';

作为替代方案,请考虑是否可以让 MyHomePagebuild() 方法返回 LoginPage 而不是 Scaffold 如果用户未登录.这可能会与后退按钮更好地交互,因为您不希望用户在完成登录之前退出登录对话框.

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.

这篇关于Flutter 重定向到 initState 上的页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆