【flutter】Flutter和原生交互提示: MissingPluginExceptio

问题描述

flutter获取电池信息的小demo
Performing hot reload...
Syncing files to device OPPO R11...
Reloaded 0 of 419 libraries in 401ms.
E/flutter ( 2440): [ERROR:flutter/shell/common/shell.cc(184)] Dart Error: Unhandled exception:
E/flutter ( 2440): MissingPluginException(No implementation found for method getBatteryLevel on channel samples.flutter.io/battery)
E/flutter ( 2440): #0 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:291:7)

**我跑了一下官方的实例代码,是可以正确获取到电池信息的, 但是官方在代码里用的是 new MethodCallHandler()
我在自己的项目里用new MethodCallHandler() 就不行 得这样子才可以 newMethodChannel.MethodCallHandler()**

dart文件

问题出现的环境背景及自己尝试过哪些方法

1.是根据文档写的,

相关代码

// 请把代码文本粘贴到下方(请勿用图片代替代码)

package com.example.batterylevel;

import android.os.Bundle;

import io.flutter.app.FlutterActivity;

import io.flutter.plugin.common.MethodCall;

import io.flutter.plugin.common.MethodChannel;

import io.flutter.plugins.GeneratedPluginRegistrant;

import android.content.ContextWrapper;

import android.content.Intent;

import android.content.IntentFilter;

import android.os.BatteryManager;

import android.os.Build.VERSION;

import android.os.Build.VERSION_CODES;

import android.os.Bundle;

public class MainActivity extends FlutterActivity {

private static final String CHANNEL = "com.example.batterylevel/battery";

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

GeneratedPluginRegistrant.registerWith(this);

new MethodChannel(getFlutterView(),CHANNEL).setMethodCallHandler(

new MethodChannel.MethodCallHandler() {

@Override

public void onMethodCall(MethodCall call, MethodChannel.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();

}

}

}

);

}

  static const platfrom = const MethodChannel("com.example.batterylevel/battery");

String _batteryLevel ="电量未知";

Future<Null> _getBatteryLevel() async{

String batteryLevel;

try{

final int result = await platfrom.invokeMethod('getBatteryLevel');

batteryLevel = "$result %";

} on PlatformException catch(e){

batteryLevel="电量获取失败:$e.message";

}

setState(() {

_batteryLevel =_batteryLevel;

});

}

你期待的结果是什么?实际看到的错误信息又是什么?

回答

【flutter】Flutter和原生交互提示: MissingPluginExceptio

IDE 默认的自动导包可能只导入到了 MethodChannel 这一层。

以上是 【flutter】Flutter和原生交互提示: MissingPluginExceptio 的全部内容, 来源链接: utcz.com/a/85254.html

回到顶部