尝试从小部件树外部监听提供程序公开的值。但我想听

时间:2020-05-23 16:42:44

标签: flutter dart state-management flutter-provider

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

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

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'

1 个答案:

答案 0 :(得分:0)

尝试执行以下操作:

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