我有一个应用程序,你需要登录才能继续(例如谷歌).

我想在需要身份验证时重定向用户.

不过,当我跑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"),
      ),
      ),
    );
  }
}

我想我做错了什么,可能是中止小部件构建导致了这一点.但是,我怎样才能做到这一点.

基本上就是:"我打开我的页面,如果没有登录,请转到登录页面."

谢谢

推荐答案

try 包装您的Navigator呼叫:

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

在计划为addPostFrameCallback的回调中:

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

您的文件顶部需要此导入:

import 'package:flutter/scheduler.dart';

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

Flutter相关问答推荐

手势捕获的异常:类型';Double';不是类型转换中类型';Double';的子类型

在Flutter 中将参数从一个类传递到另一个类

Flutter BLoC et workmanager:如何创建独特的仓库初始化模式?

遇到图像路径格式问题

无效参数(S):隔离消息中的非法参数:try 旋转图像时对象不可发送

如何删除使用isscllable时出现的左边距?

在LinkedIn上分享Fighter和Web的链接会产生不同的结果

带有图标抖动的自定义下拉按钮

如何从文本比例因子迁移到文本比例因子

为什么我们需要使用ChangeNotifierProvider而不是仅仅使用ChangeNotifier?

Riverpod中stateNotiferProvider和notifierProvider的区别

在 CircleAvatar 中放置芯片

Getx Flutter 在更新值时抛出空错误

将 onSaved(value) 从自定义 TextFormField 小部件传递给另一个?

如何使用 Riverpod 在运行时动态创建提供程序?

如何将图像网络装箱到具有边界半径的容器中

setState 不会在第一次更新 - Flutter

参数类型MaterialPageRoute不能分配给参数类型String

从 Uint8List 或图像对象创建 InputImageData 用于 Google ML Kit 人脸检测

如何验证位于 PageView 内不同页面的 TextFormFields