消费者未对 profile/release 构建中的 ChangeNotifier 更改做出反应

Consumer not reacting to changes in ChangeNotifier in profile/release builds

我有一个从 ChangeNotifier 扩展的 class,它管理一个小部件的状态:

  MainSection _section = MainSection.SETUP;

  MainSection get section => _section;

  set section(MainSection value) {
    _section = value;

    // some code

    notifyListeners();
  }

正如我所说,我用它来改变小部件的状态:

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<MainBloc>.value(
      value: _bloc,
      child: Consumer<MainBloc>(builder: (context, bloc, child) {
        _bloc = bloc;
        var body;

        switch (_bloc.section) {
          case MainSection.SETUP:
            body = _widgetFactory.createSetupWidget();
            break;
          case MainSection.WAITING:
            body = Column(
              children: <Widget>[
                Expanded(
                  child: _widgetFactory.createWaitingWidget(),
                ),
                _getBottomBar()
              ],
            );
            break;

自从我更新应用程序以使用最新的 Flutter 版本后,此机制工作正常。现在在调试模式下它在所有情况下都可以正常工作,但在配置文件或发布模式下它在应用程序的特定点不起作用,这意味着它适用于某些状态更改但对于特定更改不起作用。我不知道什么会影响它。

为什么我说它不起作用:我更改变量,调用 notifyListeners() 但消费者没有收到通知。

我使用的是提供程序依赖版本 4.3.1

扑博士:

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, v1.17.5, on Linux, locale en_US.UTF-8)
[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
[✓] Android Studio (version 4.0)
[!] IntelliJ IDEA Community Edition (version 2019.2)
    ✗ Flutter plugin not installed; this adds Flutter specific functionality.
[!] VS Code (version 1.47.3)
    ✗ Flutter extension not installed; install from
      https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter
[✓] Connected device (1 available)

我已经发现发生了什么,一些子部件正在构建方法中处理未来:

  @override
  Widget build(BuildContext context) {
    return FutureProvider<FutureBundle>.value(
        value: _bloc.getChannels(),
        initialData: FutureBundle(state: BundleState.LOADING),
        catchError: (context, error) {
          return FutureBundle(state: BundleState.ERROR, data: error);
        },
        child: Consumer<FutureBundle>(builder: (context, bundle, view) {

我根据 参考更改了此实现,一切都再次运行:

@override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: future,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return ChangeNotifierProvider<WaitingBloc>.value(
              value: _bloc,
              child: Consumer<WaitingBloc>(builder: (context, bloc, child) {

我知道这是一个老问题,它已经有了正确的答案,但这对任何人都有帮助。

同样的错误发生在我身上,因为(基本上)我从小部件树下某处的 build 方法调用 notifyListeners()。删除该调用解决了问题。

不确定为什么我的代码在调试模式下工作。