flutter 尝试从小部件树外部侦听使用provider公开的值,onSubmitted()中出错

bejyjqdl  于 2023-03-24  发布在  Flutter
关注(0)|答案(2)|浏览(157)
The following assertion was thrown while calling onSubmitted for TextInputAction.done:
    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<Counter>(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: Boxes(dependencies: [_InheritedProviderScope<Counter?>], state:
    _BoxesState#274b3)
    'package:provider/src/provider.dart':
    Failed assertion: line 274 pos 7: 'context.owner!.debugBuilding ||
          listen == false ||
          debugIsInInheritedProviderUpdate'

这个错误发生在我添加了一行将一些数据插入到列表中之后。

TextField(
        controller: _textController,
        style: const TextStyle(color: Colors.white),
        decoration: 
            const InputDecoration(
                border: 
                    OutlineInputBorder(
                        borderRadius:
                            BorderRadius.all(Radius.circular(40.0)),
                    ),
                labelText: "Enter here",
            ),
            onSubmitted: (value) {
                setState(() {
                    Provider.of<Counter>(context, listen: false); // add listen: false here
                    _boxStorage += "- ${_textController.text}\n";
                    _storage.insert(context.watch<Counter>().count, _boxStorage);
                    _saveSharedPreferences();
                    _textController.clear();
                });
            }
    ),

我已经尝试添加'Provider.of(context,listen:false)',这是错误消息中建议的解决方案。然而,这个解决方案对我不起作用,并且在运行代码后再次出现相同的错误。有人能帮忙吗?

i1icjdpr

i1icjdpr1#

代码中的要求并不十分明确。
对于行:

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

如果您不想从provider访问任何值,不知道为什么要添加此行。没有必要添加该行。

6vl6ewon

6vl6ewon2#

编辑

将“context.watch<Counter>.count”更改为context.read<Counter>.count并删除Provider.of<Counter>(context, listen: false);后问题解决

相关问题