dart 解决Flutter异常:'FlutterError(setState()或markNeedsBuild()在构建期间调用,'

vltsax25  于 2023-07-31  发布在  Flutter
关注(0)|答案(1)|浏览(197)

我正在完成FreeCodeCamp 37 hour Flutter tutorial的第12章(时间戳11:20:59),遇到了一个异常,阻止我继续。你能帮我解决这个问题吗?
错误文本:

Exception has occurred.
FlutterError (setState() or markNeedsBuild() called during build.
This Overlay widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase.
The widget on which setState() or markNeedsBuild() was called was:
  Overlay-[LabeledGlobalKey<OverlayState>#f420f]
The widget which was currently being built when the offending call was made was:
  FutureBuilder<FirebaseApp>)

字符串
代码Navigator.of(context).push(这一行出错
这一行是这段代码的一部分:

class HomePage extends StatelessWidget {
  const HomePage({super.key});

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Home'),
      ),
      body: FutureBuilder(
        future: Firebase.initializeApp(
          options: DefaultFirebaseOptions.currentPlatform,
        ),
        builder: (context, snapshot) {
          switch (snapshot.connectionState) {
            case ConnectionState.done:
              final user = FirebaseAuth.instance.currentUser;
              if (user?.emailVerified ?? false) {
                return const Text('Done');
              } else {
                Navigator.of(context).push(
                  MaterialPageRoute(
                    builder: (context) => const VerifyEmailView(),
                  ),
                );
              }
              return const Text('Done');
            default:
              return const Text('Loading...');
          }
        },
      ),
    );
  }
}


我希望代码显示VerifyEmailView类,HomePage类显示为默认文本'Loading...'

91zkwejq

91zkwejq1#

您可以延迟一帧,然后推送到下一个路由

WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => const VerifyEmailView(),
      ),
    );
  });

字符串

相关问题