在initState中重定向到另一个页面的Flutter实现

52

我有一个应用程序,需要登录才能继续(例如使用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"),
      ),
      ),
    );
  }
}

我猜我做错了什么,也许是中止小部件构建导致了这个问题。但是,我该如何实现这一点。

基本上: "我进入我的页面,如果没有登录,就转到登录页面"

谢谢, Alexi

4个回答

88

尝试包装您的Navigator调用:

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

在使用addPostFrameCallback方法进行调度的回调函数中:

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

你需要在文件顶部引入以下内容:

import 'package:flutter/scheduler.dart';

作为另一种选择,考虑如果未登录用户只需使MyHomePagebuild()方法返回一个LoginPage而不是Scaffold。这样可能会更好地与后退按钮交互,因为您不希望用户在完成登录之前退出登录对话框。


8
你的第二个选择比第一个好得多。我使用了这个。谢谢Collin,非常有用的答案(像往常一样)。 - Alexi Coard
1
我在第一个解决方案中遇到问题,context 未定义。 - temirbek
1
你把那个scheduler绑定在哪里?谢谢。 - Alberto Acuña
你们从哪里获取上下文的??????它是未定义的。 - b.john
@b.john widget的State有一个context实例属性,你可能正在尝试在无状态小部件或任何其他不是State<T>的类中调用它。此外,我建议在initState方法内调用它,因为我不太确定在build方法内调用它时所有可能的副作用。 - Guilherme Matuella

23

覆盖initState()函数并使用以下任何一种方式:

  • Future

    Future(() {
      Navigator.of(context).pushNamed('login');
    });
    
  • 计时器:

    Timer.run(() { // import 'dart:async:
      Navigator.of(context).pushNamed('login');
    });
    

1
未定义名称“Timer”。你从哪里导入它的? - Paktalin
2
@Paktalin 导入 dart:async; - CopsOnRoad
未来对我不起作用。Timer.run运行良好! - Mark Choi

4
另一种方法是在打开需要身份验证的新页面之前执行登录检查。
主页面被保留为“欢迎”/信息页面,当用户点击菜单项时,将执行登录检查。
已登录:新页面已打开。
已注销:登录页面已打开。
对我来说可行 :)

2
您还可以执行以下操作:
scheduleMicrotask(() => Navigator.of(context).push(MaterialPageRoute(builder: (context) => YourComponent())));

这段代码对我有效,这是我代码的一个示例: Navigator.of(context).push(MaterialPageRoute(builder: ((context) => const Home()))); - prawito hudoro

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接