![](/img/trans.png)
[英]Flutter based Android app throwing MissingPluginException(No implementation found for method on channel)
[英]Can't resolve flutter native communication error - Unhandled Exception No implementation found for method on Channel
我剛剛從 flutter.dev 復制代碼並修改它並得到以下錯誤
E/flutter ( 2639): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] 未處理的異常:MissingPluginException(未找到方法 myNativeFunction 在通道 My Channel 上的實現) * 我想打印來自 Native java 代碼的消息至 Flutter UI *
This is my Main.dart
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
static const platform = const MethodChannel('My Channel');
String message = "No Message from Native App";
Future<void> callNative() async {
String messageFromNative = "No message from Native";
try {
messageFromNative = await platform.invokeMethod('myNativeFunction');
print(messageFromNative);
} on PlatformException catch (e) {
print("error + '${e.message}' ");
message = "Failed to get Native App function: '${e.message}'.";
}
setState(() {
message = messageFromNative;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Native Demo'),
),
body: Center(
child: Column(
children: [
Text(message),
RaisedButton(child: Text('Native '), onPressed: callNative)
],
),
),
),
);
}
}
This is my MainActivity.java
package com.example.batterylevel;
import android.util.Log;
import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodChannel;
public class MainActivity extends FlutterActivity {
public static final String CHANNEL="MyChannel";
@Override
public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
super.configureFlutterEngine(flutterEngine);
new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
.setMethodCallHandler(
(call, result) -> {
if(call.method.equals("myNativeFunction"))
{
String messageToFlutter=myNativeFunction();
result.success(messageToFlutter);
}else {
result.notImplemented();
Log.d("RD","else");
}
}
);
}
String myNativeFunction()
{
return "Message from Android";
}
}
在MainActivity
中,方法通道名稱應與 dart 中定義的方法通道名稱匹配。
Dart
static const platform = const MethodChannel('My Channel');
Java
public static final String CHANNEL = "My Channel"; // on dart side it's "My Channel", but you've written "MyChannel"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.