消费者和供应商的问题

时间:2021-03-29 23:04:54

标签: flutter flutter-provider

您好,我的 Flutter 应用程序使用提供者和消费者时遇到问题。

我在调试器中遇到这个问题时,一切正常:

════════ Exception caught by foundation library ════════════════════════════════
The following assertion was thrown while dispatching notifications for CatergoryProvider:
setState() or markNeedsBuild() called during build.

This _InheritedProviderScope<CatergoryProvider> 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: _InheritedProviderScope<CatergoryProvider>
    value: Instance of 'CatergoryProvider'
    listening to value
The widget which was currently being built when the offending call was made was: Consumer<CatergoryProvider>
    dirty
    dependencies: [_InheritedProviderScope<CatergoryProvider>]
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      _InheritedProviderScopeElement.markNeedsNotifyDependents
package:provider/src/inherited_provider.dart:496
#3      ChangeNotifier.notifyListeners
package:flutter/…/foundation/change_notifier.dart:243
#4      CatergoryProvider.setLoading
package:quizz_app/provider/catergoryProvider.dart:43
...
The CatergoryProvider sending notification was: Instance of 'CatergoryProvider'

这里是有问题的消费者:

 Consumer<CatergoryProvider>(
            builder: (context, catergory, child) {
              if (!catergory.isLoading() && !catergory.isList()) {
                catergory.fetchCatergory();
              }
              catergories = catergory.getList();
              return catergory.isLoading()
                  ? ModalProgressHUD(
                      opacity: 0,
                      inAsyncCall: catergory.isLoading(),
                      child: Container())
                  : catergoryPage(catergories, context);
            },
          ),

这就是堆栈跟踪引导我到的地方:

  void setLoading(value) {
    loading = value;
    notifyListeners();
  }

1 个答案:

答案 0 :(得分:0)

看起来您可能在构建方法中调用 setLoading(value)。这将尝试在构建小部件期间调用 notifyListeners() 时触发小部件的重建。

考虑在等待异步操作时使用 FutureBuilderStreamBuilder 来更改状态。