我需要在flutter中从原生的android java Activity中调用一个写在.dart文件中的dart方法,我该怎么做?
pbgvytdp1#
在Flutter
void main() { runApp(MyApp()); } class MyApp extends StatelessWidget{ @override Widget build(BuildContext context) { return MaterialApp( home: ScreenPage(), ); } } class ScreenPage extends StatefulWidget { @override _ScreenPageState createState() => _ScreenPageState(); } class _ScreenPageState extends State<ScreenPage> { static const platform = const MethodChannel("myChannel"); @override void initState() { platform.setMethodCallHandler(nativeMethodCallHandler); super.initState(); } Future<dynamic> nativeMethodCallHandler(MethodCall methodCall) async { print('Native call!'); switch (methodCall.method) { case "methodNameItz" : return "This data from flutter....."; break; default: return "Nothing"; break; } } @override Widget build(BuildContext context) { //return (); } }
在Java
import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import io.flutter.app.FlutterActivity; import io.flutter.plugin.common.MethodChannel; //import io.flutter.view.FlutterNativeView; public class MyJavaFile extends FlutterActivity { Button clickMeButton; MethodChannel channel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); channel = new MethodChannel(getFlutterView(), "myChannel"); setContentView(R.layout.home_activity); clickMeButton = findViewById(R.id.clickMeButton); clickMeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { channel.invokeMethod("methodNameItz", null, new MethodChannel.Result() { @Override public void success(Object o) { Log.d("Results", o.toString()); } @Override public void error(String s, String s1, Object o) { } @Override public void notImplemented() { } }); } }); } }
gmxoilav2#
1.添加通道(与您的payactivity通道相同)并在dart代码中创建sethandler方法。static const platform = const MethodChannel('flutter.native/helper'); System. out. println();1.在dartcode中创建一个处理方法:Future nativeMethodCall(MethodCall methodCall){ switch(methodCall.method){ case“UpdatePayment”:........1.在activity/java代码中调用此方法:methodChannel.invokeMethod(“UpdatePayment”,null)
2条答案
按热度按时间pbgvytdp1#
在Flutter
在Java
gmxoilav2#
1.添加通道(与您的payactivity通道相同)并在dart代码中创建sethandler方法。static const platform = const MethodChannel('flutter.native/helper'); System. out. println();
1.在dartcode中创建一个处理方法:Future nativeMethodCall(MethodCall methodCall){ switch(methodCall.method){ case“UpdatePayment”:........
1.在activity/java代码中调用此方法:methodChannel.invokeMethod(“UpdatePayment”,null)