我有2个项目。一个是主项目,另一个是库项目。 在主项目中添加了以下功能。
dependencies:
flutter:
sdk: flutter
library_project:
path: D:\****\Flutter Projects\library-project
现在我可以访问library-project的任何类和小部件,但是 我必须从主项目访问libarry项目中的Java本机方法。 这是我从main到库项目访问本机java的方式。以下函数在库的类函数中,我通过导入函数的类从主项目访问它。
static const platform = const MethodChannel('example.flutter.io/test');
static Future<void> testMehtod() async {
try {
final int result = await platform.invokeMethod("getBatteryLevel");
} on PlatformException catch (e) {
print(e.message);
}
}
这是Java本机类
public class MainActivity extends FlutterActivity {
private static final String CHANNEL = "example.flutter.io/test";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
new MethodCallHandler() {
@Override
public void onMethodCall(MethodCall call, Result result) {
if (call.method.equals("getBatteryLevel")) {
int batteryLevel = getBatteryLevel();
if (batteryLevel != -1) {
result.success(batteryLevel);
} else {
result.error("UNAVAILABLE", "Battery level not available.", null);
}
} else {
result.notImplemented();
}
}
});
}
}
private int getBatteryLevel() {
int batteryLevel = -1;
if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
BatteryManager batteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE);
batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
} else {
Intent intent = new ContextWrapper(getApplicationContext()).
registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
batteryLevel = (intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100) /
intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
}
return batteryLevel;
}
这是我要弄的东西。
[错误:flutter / shell / common / shell.cc(186)] Dart错误:未处理的异常: E / flutter(25932):MissingPluginException(在通道example.flutter.io/test上未找到方法testmethod的实现) E / flutter(25932):#0 MethodChannel.invokeMethod(软件包:flutter / src / services / platform_channel.dart:291:7) E /颤振(25932): E / flutter(25932):#1 Utils.testMethod(程序包:library_project / utils / utils.dart:16:41) E /颤振(25932): E / flutter(25932):#2 _MyHomePageState._incrementCounter。 (package:arche_isp_dualmode / main.dart:60:13)