Flutter之原生交互(Android)

Flutter之原生交互(Android)

需求: flutter创建一个页面,页面上有个按钮,点击按钮,跳转android原生页面,并传递数据

Flutter端代码

class JumpToAndroid extends StatelessWidget{
	// 确定MethodChannel中name的唯一性
  static const jumpPlugin = const MethodChannel('com.barray.flutterapp/plugin');
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("跳转到原生页面"),),
      body: Container(
        child: FlatButton(onPressed: (){
          jumpToAndroid();
        }, child: Text("跳转Android页面")),
      ),
    );
  }
	// 异步方法
  Future jumpToAndroid() async{
    Map map = {"flutter_data":"张三"};
	// 跳转并传递数据
    var result = await jumpPlugin.invokeMethod("androidLocal",map);
	// 打印android返回的参数
    print("result--->$result");
  }
}

Android端代码

public class MainActivity extends FlutterActivity {
	// 唯一性
    public static final String CHANNEL = "com.barray.flutterapp/plugin";
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getFlutterEngine() != null) {
            new MethodChannel(getFlutterEngine().getDartExecutor().getBinaryMessenger(), CHANNEL)
                    .setMethodCallHandler((call, result) -> {
						// flutter端方法名androidLocal
                        if ("androidLocal".equals(call.method)) {
							// 获取传递的数据,并跳转
                            Intent intent = new Intent(this, AndroidLocalActivity.class);
                            String text = call.argument("flutter_data");
                            if (!TextUtils.isEmpty(text)) {
                                intent.putExtra(AndroidLocalActivity.NAME, text);
                            }
                            startActivity(intent);
							// 通知flutter端返回的结果
                            result.success("success");
                        } else {
                            result.notImplemented();
                        }
                    });
        }
    }
}

你可能感兴趣的:(Flutter,android,flutter,交互)