【问题标题】:Tried to listen to a value exposed with provider, from outside of the widget tree. But I want to listen to it试图从小部件树外部侦听提供者公开的值。但我想听
【发布时间】:2020-09-10 11:53:45
【问题描述】:

我正在尝试侦听对我的提供程序模型中的字符串变量所做的更新。 Flutter 建议我不要听它们,因为听者显然不在小部件树上下文中,我不明白为什么。

我正在调用侦听器的小部件是一个 IconButton,它驻留在有状态小部件类中,该类是进入 ListView 构建器的许多其他项目的列表项的一部分。我想从侦听器中获取字符串,然后在 Stateful 小部件类中调用 setState 以仅从按下其 IconButton 的列表项中更新列表项。我不想更新 ListView 构建器中的每个列表项。否则,我会直接将侦听器放在 Text 字段上。希望这是有道理的.. :)

IconButton(
    icon: Icon(Icons.mic),
    onPressed: () {
        Provider.of<VoiceFunctions>(context, listen: false).startFirstVoiceListener();
        var newWords = Provider.of<VoiceFunctions>(context, listen: true).outputString;
        print(newWords);
}),

我尝试将 outputString 的侦听器移动到它自己的函数中,以便将其移出 onPressed() ,但这会产生相同的错误。

完整的堆栈跟踪:


════════ Exception caught by gesture ═══════════════════════════════════════════
The following assertion was thrown while handling a gesture:
Tried to listen to a value exposed with provider, from outside of the widget tree.

This is likely caused by an event handler (like a button's onPressed) that called
Provider.of without passing `listen: false`.

To fix, write:
Provider.of<VoiceFunctions>(context, listen: false);

It is unsupported because may pointlessly rebuild the widget associated to the
event handler, when the widget tree doesn't care about the value.

The context used was: FlashcardItemWidget(dependencies: [MediaQuery, _LocalizationsScope-[GlobalKey#02e26], _InheritedTheme], state: _FlashcardItemWidgetState#51c99)
'package:provider/src/provider.dart':
Failed assertion: line 191 pos 7: 'context.owner.debugBuilding ||
          listen == false ||
          debugIsInInheritedProviderUpdate'

【问题讨论】:

    标签: flutter dart state-management flutter-provider


    【解决方案1】:

    尝试:

    Provider.of<VoiceFunctions>(context, listen: false);
    

    【讨论】:

      猜你喜欢
      • 2020-05-21
      • 2020-12-14
      • 2021-11-13
      • 1970-01-01
      • 2021-02-20
      • 2021-12-24
      • 2016-06-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多