简体   繁体   中英

How to call a Dart method from an Android java Activity in Flutter?

我需要从原生 android java 活动中调用一些 .dart 文件中编写的 dart 方法,我该怎么做?

In 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 ();
  }
 
}

In 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() {
                    }

                });

            }
        });



    }


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM