Why Flutter GlobalKey's currentState is NULL when accessed from other file

痞子三分冷 提交于 2019-11-29 12:46:48

That is due to how dart import works.

In dart, there is two way to import sources :

  • import './relative/path.dart'
  • import 'myApp/absolute/path.dart'

The thing is, they are not compatible with each others. Both these imports will have a different runtimeType.

But how is that a problem ? I never used relative import

That's a problem, because in some situations you implicitly use "relative imports" : When using a class A defined in foo.dart inside foo.dart.

So, how do I solve the problem ?

There are multiple solutions :

  • Have everything related to your class App should be inside the same file. (That's the recommended thing in dart)
  • Extract App into it's own file. And import it everywhere using absolute imports.
  • Don't use GlobalKey to begin with. As your use case is definitely in the scope of InheritedWidget.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!