你如何在 Riverpod 中创建和修改一个用于 flutter 的布尔状态提供者?

问题描述

我正在尝试创建一个全局提供程序,它将作为提供程序系列的一部分保存一个布尔值

final PaginationProvider = StateProvider.family((ref,id) => true);

但是我尝试像其他提供商一样设置该值的尝试失败了

context.read(PaginationProvider(0)).state = false;

具体的错误

Unhandled Exception: setState() or markNeedsBuild() called during build.
This UncontrolledProviderScope 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:
  UncontrolledProviderScope
The widget which was currently being built when the offending call was made was:
  Builder

解决方法

好吧,我什至不知道为什么,但这解决了问题。

把它留在这里以防其他人有这个问题

    Future.delayed(
        Duration.zero,() => context
            .read(PaginationProvider(0))
            .state = false);