[英]Passing BuildContext to non builder methods
I was wondering if passing around BuildContext objects that we receive in the build method is a good idea?我想知道传递我们在 build 方法中收到的 BuildContext 对象是否是个好主意? Basically pass it to places that are non-builder methods.
基本上将它传递给非构建器方法的地方。
For example, I may pass it to my ViewModel in the case of the Provider package.例如,在 Provider package 的情况下,我可以将它传递给我的 ViewModel。 Is it a good thing to do?
这是一件好事吗?
Or will it have repercussions?还是会产生影响?
Passing BuildContext
around is generally a bad idea.传递
BuildContext
通常是一个坏主意。
This object is not made to be passed around.这个 object 不是用来传递的。 If you need a
BuildContext
, instead create a new one (using a custom StatelessWidget
or Builder
).如果您需要
BuildContext
,请创建一个新的(使用自定义StatelessWidget
或Builder
)。
Failing to do so may cause bugs that are hard to debug (such that causing a ProviderNotFoundException
), and creating a new BuildContext
instead of reusing an existing one can improve performances.不这样做可能会导致难以调试的错误(例如导致
ProviderNotFoundException
),并且创建新的BuildContext
而不是重用现有的可以提高性能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.