Необработанное исключение: setState() или markNeedsBuild(), вызываемые во время сборки. внутри BlocListener

#flutter #bloc #statefulwidget #flutter-state

#flutter #блок #statefulwidget #флаттер-состояние

Вопрос:

Я новичок в flutter и пытаюсь реализовать блок в приложении. Я хочу изменить значение флага с помощью события и обновить состояние после изменения логического значения флага. Я попытался setState() внутри прослушивателя блога, но возвращал следующее исключение.

 [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: setState() or markNeedsBuild() called during build.
E/flutter ( 2570): 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.
E/flutter ( 2570): The widget on which setState() or markNeedsBuild() was called was:
E/flutter ( 2570):   Overlay-[LabeledGlobalKey<OverlayState>#94b3b]
E/flutter ( 2570): The widget which was currently being built when the offending call was made was:
E/flutter ( 2570):   ActivitySignUpWidget
E/flutter ( 2570): #0      Element.markNeedsBuild.<anonymous closure> (package:flutter/src/widgets/framework.dart:4211:11)
E/flutter ( 2570): #1      Element.markNeedsBuild (package:flutter/src/widgets/framework.dart:4226:6)
E/flutter ( 2570): #2      State.setState (package:flutter/src/widgets/framework.dart:1260:14)
E/flutter ( 2570): #3      OverlayState.insert (package:flutter/src/widgets/overlay.dart:326:5)
E/flutter ( 2570): #4      ToastView.createView (package:toast/toast.dart:67:18)
E/flutter ( 2570): #5      Toast.show (package:toast/toast.dart:19:15)
E/flutter ( 2570): #6      _ActivitySignUpState._selectCountrCode (package:crm_application_devops/signup/ActivitySignUp.dart:471:11)
E/flutter ( 2570): #7      _ActivitySignUpState._createForm (package:crm_application_devops/signup/ActivitySignUp.dart:219:53)
E/flutter ( 2570): #8      _ActivitySignUpState.build (package:crm_application_devops/signup/ActivitySignUp.dart:115:42)
E/flutter ( 2570): #9      StatefulElement.build (package:flutter/src/widgets/framework.dart:4663:28)
E/flutter ( 2570): #10     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4546:15)
E/flutter ( 2570): #11     StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4719:11)
E/flutter ( 2570): #12     Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
E/flutter ( 2570): #13     BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2667:33)
E/flutter ( 2570): #14     WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:866:20)
E/flutter ( 2570): #15     RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:286:5)
E/flutter ( 2570): #16     SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1117:15)
E/flutter ( 2570): #17     SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1056:9)
E/flutter ( 2570): #18     SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:972:5)
E/flutter ( 2570): #19     _rootRun (dart:async/zone.dart:1190:13)
E/flutter ( 2570): #20     _CustomZone.run (dart:async/zone.dart:1093:19)
E/flutter ( 2570): #21     _CustomZone.runGuarded (dart:async/zone.dart:997:7)
E/flutter ( 2570): #22     _invoke (dart:ui/hooks.dart:253:10)
E/flutter ( 2570): #23     _drawFrame (dart:ui/hooks.dart:211:3)
E/flutter ( 2570): 
  

Ниже приведен мой код. помогите мне решить эту проблему. Заранее спасибо.

 @override
  Widget build(BuildContext context) {
    signupBloc = BlocProvider.of<SignUpBloc>(context);
    return Scaffold(
      body: Container(
        color: Colors.white,
        child: SafeArea(
          child: Column(children: [
            Column(
              children: [
                BlocListener<SignUpBloc, SignUpState>(
                  listener: (context, state) {
                    if(state is ContryCodeChangeState){
                      print("State called");
                      setState(() {
                        valueOfInput = state.getContryCodeValue;
                      });
                    }
                  },
                  child: Container(
                    child: Column(
                      children: [
                        _signUpHeader(),
                        Padding(
                          padding: const EdgeInsets.only(top: 30.0),
                          child: jsonStringValues != null
                              ? Text(
                                  jsonStringValues[
                                      "Sign_up_to_become_a_member"],
                                  style: TextStyle(
                                      color: Colors.purpleAccent,
                                      fontSize: 16.0,
                                      fontWeight: FontWeight.bold),
                                )
                              : null,
                        ),
                        _createAccount(),
                        Center(
                            child: Padding(
                                padding: EdgeInsets.only(right: 30, left: 30),
                                child: Visibility(
                                  visible: true,
                                  child: _createForm(),
                                ))),
                        Padding(
                          padding: const EdgeInsets.only(top: 16),
                          child: Align(
                            alignment: FractionalOffset.bottomCenter,
                            child: Text(
                              "By sign up you are agreeing to th Tamp;C",
                              style:
                                  TextStyle(color: Colors.black, fontSize: 11),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ]),
        ),
      ),
    );
  }
  

Ответ №1:

 if(mounted){
 //call set state here
}