首页 > 解决方案 > 在构建错误期间调用了我的 setState() 或 markNeedsBuild()。你能帮我么?

问题描述

首先,我不得不说,我也检查了有关此错误的其他问题,但找不到解决方案。

我收到这样的错误:

════════ Exception caught by widgets library ═══════════════════════════════════
The following assertion was thrown building LoginPage(dirty, dependencies: [MediaQuery]):
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>#c8e35]
    state: OverlayState#58ca1(entries: [OverlayEntry#26031(opaque: true; maintainState: false), OverlayEntry#307a6(opaque: false; maintainState: true), OverlayEntry#70b4a(opaque: false; maintainState: false), OverlayEntry#4c25b(opaque: false; maintainState: true)])
The widget which was currently being built when the offending call was made was: LoginPage
The relevant error-causing widget was
LoginPage
lib\…\screens\landing_page.dart:20
When the exception was thrown, this was the stack
#0      Element.markNeedsBuild.<anonymous closure>
package:flutter/…/widgets/framework.dart:4138
#1      Element.markNeedsBuild
package:flutter/…/widgets/framework.dart:4153
#2      State.setState
package:flutter/…/widgets/framework.dart:1287
#3      OverlayState.rearrange
package:flutter/…/widgets/overlay.dart:436
#4      NavigatorState._flushHistoryUpdates
package:flutter/…/widgets/navigator.dart:4043
...


════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/navigator.dart': Failed assertion: line 4517 pos 12: '!_debugLocked': is not true.
The relevant error-causing widget was
LoginPage
lib\…\screens\landing_page.dart:20

E/flutter ( 4507): #5      _CustomZone.runUnary (dart:async/zone.dart:1265:19)
E/flutter ( 4507): #6      _FutureListener.handleValue (dart:async/future_impl.dart:152:18)
E/flutter ( 4507): #7      Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:704:45)
E/flutter ( 4507): #8      Future._propagateToListeners (dart:async/future_impl.dart:733:32)
E/flutter ( 4507): #9      Future._completeWithValue (dart:async/future_impl.dart:539:5)
E/flutter ( 4507): #10     Future._asyncCompleteWithValue.<anonymous closure> (dart:async/future_impl.dart:577:7)
E/flutter ( 4507): #11     _rootRun (dart:async/zone.dart:1354:13)
E/flutter ( 4507): #12     _CustomZone.run (dart:async/zone.dart:1258:19)
E/flutter ( 4507): #13     _CustomZone.runGuarded (dart:async/zone.dart:1162:7)
E/flutter ( 4507): #14     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1202:23)
E/flutter ( 4507): #15     _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
E/flutter ( 4507): #16     _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)

我的主要方法是这样的:

 main(List<String> args) async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(
     MultiProvider(
       providers: [
         ChangeNotifierProvider(create:(_)=> AuthService()),
       ],
       child: MyApp()),
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    
    
    return MaterialApp(
      theme: ThemeData(fontFamily: GoogleFonts.oxanium().fontFamily),
      debugShowCheckedModeBanner: false,
     initialRoute: "/",
      routes: {
        '/': (context) => LandingPage(),
        'login': (context) => LoginPage(),
        'register': (context) => RegisterPage(),
        'game': (context) => GamePage(),
        'main': (context) => MainPage(),
        'profile': (context) => ProfilePage(),
        'beforeQ': (context) => BeforeQuestionPage(),
        'editProfile': (context) => EditProfilePage(),
        'question': (context) => QuestionPage(),
        'shop': (context) => ShopPage(),
      },
    );
  }
}

我的登陆页面是这样的:

class LandingPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final auth = Provider.of<AuthService>(context);
    switch (auth.userState) {
      case UserStates.LoggingIn:
        return Scaffold(
          body: Center(
            child: CircularProgressIndicator(),
          ),
        );

      case UserStates.NotLoggedIn:
        return LoginPage();

      case UserStates.LoggedIn:
        return MainPage();

      default:
        return Scaffold(
          body: Center(
            child: CircularProgressIndicator(),
          ),
        );
    }

    
  }
}

正如我所说,我尝试尝试其他问题的解决方案建议,但它无法解决我的问题。这就是我打开这个线程的原因。知道我的问题的任何解决方案的人可以给出答案吗?从现在开始谢谢你

标签: flutterstreamfuturesetstateprovider

解决方案


您可以使用Future.delayed

Future.delayed(Duration.zero, () async {

    setState(() {});

});

推荐阅读