如何在Flutter中在一切之前调用一个MethodChannel?

huangapple go评论100阅读模式
英文:

How to make a methodchannel call before everything in flutter?

问题

在我的项目中,我的Flutter模块需要通过MethodChannel从本地获取一些信息。

我希望在根部件显示之前就返回这个方法通道调用(因为这个部件将使用这些信息来获取数据并显示)。

我已经尝试在main()中的runApp之前调用,但这个调用似乎太早了,无法正常工作。而且,我不知道是否将main声明为异步是一个不好的主意。

还有其他更好的方法来完成这种工作吗?

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  MethodChannel platform = const MethodChannel('flutter.km.methodchannel');
  var nativeInfo = await platform.invokeMethod('getNativeInfo');
  runApp(const MyApp());
}
英文:

In my project , my flutter module need to fetch some information from native with MethodChannel.

And I want this method channel call is returned before even the root widget display (because this widget will use this information to fetch data and display)

I have tried invoking before runApp in main(). but this call seems too early to work . And I don't know whether is a bad idea to make main async

Any other better way to do this kind of work?

    void main() async{
      WidgetsFlutterBinding.ensureInitialized();
      MethodChannel platform = const MethodChannel('flutter.km.methodchannel');
      var nativeInfo = await platform.invokeMethod('getNativeInfo');
      runApp(const MyApp());
    }

答案1

得分: 1

你使用 async-await 沒有问题。此 Stack Overflow 问题在以下链接中有详细信息,请查看:

https://stackoverflow.com/questions/56129121/good-or-bad-declaring-main-method-async-in-dart-flutter

英文:

There is no problem with your use of async-await. This question on stackoverflow has detailed information in the link below. please look there.

https://stackoverflow.com/questions/56129121/good-or-bad-declaring-main-method-async-in-dart-flutter

答案2

得分: 0

main() 内部调用 MethodChannel 的问题在于,从本地代码的角度来看,可能尚未调用 'GeneratedPluginRegistrant.register()',因此通道尚未建立。

英文:

The problem with invoking a MethodChannel inside main() is that on the native side your 'GeneratedPluginRegistrant.register()' call hasn't probably being made yet, so the channel hasn't yet been established.

huangapple
  • 本文由 发表于 2023年3月9日 14:59:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75681353.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定