Home > Net >  Flutter: Why do I get an error when using the setState() method?
Flutter: Why do I get an error when using the setState() method?

Time:11-01

I added setState() method and got an error. Terminal error (I'm using flutter run -d chrome --web-hostname localhost --web-port 7357 command, so it's in terminal):

══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following assertion was thrown building StreamBuilder<List<BusinessModel>>(dirty, state:
_StreamBuilderBaseState<List<BusinessModel>, AsyncSnapshot<List<BusinessModel>>>#918d6):
setState() or markNeedsBuild() called during build.
This BusinessList 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:
  BusinessList
The widget which was currently being built when the offending call was made was:
  StreamBuilder<List<BusinessModel>>

The relevant error-causing widget was:
  StreamBuilder<List<BusinessModel>>
  StreamBuilder:file:///Users/name/development/projects/flutter/project-id/lib/screens/tabs/a_tab_screen.dart:52:
  12

When the exception was thrown, this was the stack:
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 266:49      throw_
packages/flutter/src/widgets/framework.dart 4549:11                               <fn>
packages/flutter/src/widgets/framework.dart 4563:14                               markNeedsBuild
packages/flutter/src/widgets/framework.dart 1134:5                                setState
packages/project-id/screens/tabs/a_tab_screen.dart 67:15  <fn>
packages/flutter/src/widgets/async.dart 444:81                                    build
packages/flutter/src/widgets/async.dart 124:48                                    build
packages/flutter/src/widgets/framework.dart 4992:27                               build
packages/flutter/src/widgets/framework.dart 4878:15                               performRebuild
packages/flutter/src/widgets/framework.dart 5050:11                               performRebuild
packages/flutter/src/widgets/framework.dart 4604:5                                rebuild
packages/flutter/src/widgets/framework.dart 2667:18                               buildScope
packages/flutter/src/widgets/binding.dart 882:9                                   drawFrame
packages/flutter/src/rendering/binding.dart 378:5                                 [_handlePersistentFrameCallback]
packages/flutter/src/scheduler/binding.dart 1175:15                               [_invokeFrameCallback]
packages/flutter/src/scheduler/binding.dart 1104:9                                handleDrawFrame
packages/flutter/src/scheduler/binding.dart 1015:5                                [_handleDrawFrame]
lib/_engine/engine/platform_dispatcher.dart 1168:13                               invoke
lib/_engine/engine/platform_dispatcher.dart 219:5                                 invokeOnDrawFrame
lib/_engine/engine/initialization.dart 195:45                                     <fn>
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 334:14  _checkAndCall
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 339:39  dcall

════════════════════════════════════════════════════════════════════════════════════════════════════

My code:

StreamBuilder<List<Model>>(
  stream: db.stream(),
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting) {
      return …;
    }

    final List<Model>? data = snapshot.data;

    if (data != null) {
      for (int i = 0; i < data.length; i  ) {
        if (data[i].aboutLastUpdated.toDate().month == Timestamp.now().toDate().month) {
          setState(() {
            final_data.add(data[i]);
          });
        }
      }
      return …;
    }

    return …;
  },
);

Feel free to comment if you need more information!

How to fix this error? I would appreciate any help. Thank you in advance!

CodePudding user response:

This error means that you are calling setState((){}) during the build which do multiple build at the same time.

Do not call setState in the widget build. The builder from the stream is already reloading the widgets when data are ready

  • Related