我在Flutter应用程序中添加了原生Android主屏幕小部件.
在我的AppWidgetProvider
实现中,我想onUpdate()
使用平台通道在我的方法中调用dart代码.
这可能吗?如果是这样,怎么能实现呢?
我目前的Android(Java)代码:
package com.westy92.checkiday; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.Context; import android.util.Log; import io.flutter.plugin.common.MethodChannel; import io.flutter.view.FlutterNativeView; public class HomeScreenWidget extends AppWidgetProvider { private static final String TAG = "HomeScreenWidget"; private static final String CHANNEL = "com.westy92.checkiday/widget"; private static FlutterNativeView backgroundFlutterView = null; private static MethodChannel channel = null; @Override public void onEnabled(Context context) { Log.i(TAG, "onEnabled!"); backgroundFlutterView = new FlutterNativeView(context, true); channel = new MethodChannel(backgroundFlutterView, CHANNEL); } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { Log.i(TAG, "onUpdate!"); if (channel != null) { Log.i(TAG, "channel not null, invoking dart method!"); channel.invokeMethod("foo", "extraJunk"); Log.i(TAG, "after invoke dart method!"); } } }
飞镖码:
void main() { runApp(Checkiday()); } class Checkiday extends StatefulWidget { @override _CheckidayState createState() => _CheckidayState(); } class _CheckidayState extends State{ static const MethodChannel platform = MethodChannel('com.westy92.checkiday/widget'); @override void initState() { super.initState(); platform.setMethodCallHandler(nativeMethodCallHandler); } Future nativeMethodCallHandler(MethodCall methodCall) async { print('Native call!'); switch (methodCall.method) { case 'foo': return 'some string'; default: // todo - throw not implemented } } @override Widget build(BuildContext context) { // ... } }
当我将小部件添加到我的主屏幕时,我看到:
I/HomeScreenWidget(10999): onEnabled! I/HomeScreenWidget(10999): onUpdate! I/HomeScreenWidget(10999): channel not null, invoking dart method! I/HomeScreenWidget(10999): after invoke dart method!
但是,我的dart代码似乎没有接收到调用.