英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论