我是新手。我想在Android和Flutter之间进行交流。我已经使用Method通道从flutter中打开了一个android活动。现在从当前的android活动开始。我想单击一个按钮来打开dart文件。如何在Flutter中实现这一目标?
//这是主要的。 dart类,我已经使用方法通道从中打开了一个活动。
class Communication extends StatefulWidget
{
@override
State<StatefulWidget> createState() {
return MyCommunication();
}
}
class MyCommunication extends State<Communication>
{
static const platform = const MethodChannel("test_activity");
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Container(
child: getNewActivity(),
),
)
/*new MaterialButton(
child: const Text('Open Screen'),
elevation: 5.0,
height: 48.0,
minWidth: 250.0,
color: Colors.blue,
textColor: Colors.white,
onPressed: () {
_getNewActivity();
})*/
);
}
getNewActivity() async{
try {
await platform.invokeMethod('startNewActivity');
} on PlatformException catch (e) {
print(e.message);
}
}
}
//这是我的主要活动
MainActivity()类:FlutterActivity(){
private val CHANNEL = "test_activity"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
GeneratedPluginRegistrant.registerWith(this)
MethodChannel(flutterView, CHANNEL).setMethodCallHandler(
object : MethodChannel.MethodCallHandler {
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
if(call.method.equals("startNewActivity")) {
startNewActivity()
}
}
})
}
private fun startNewActivity() {
val intent = Intent(this, SecondActivity::class.java)
startActivity(intent)
}
}
///这是第二个活动,我必须打开其中包含一些小部件的dart文件。
class SecondActivity : AppCompatActivity(), View.OnClickListener {
override fun onClick(p0: View?) {
when(p0!!.id)
{
R.id.btn ->
{
var intent = Intent(this, MainActivity::class.java)
intent.setAction(Intent.ACTION_RUN)
intent.putExtra("route","screen2");
startActivity(intent);
}
}
}
var button:Button?=null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.second_actvity)
button=findViewById(R.id.btn);
button!!.setOnClickListener(this)
// setSupportActionBar(toolbar)
// Now get the support action bar
val actionBar = supportActionBar
// Set toolbar title/app title
actionBar!!.title = "Android Component"
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
}
答案 0 :(得分:3)
使用方法Channel在Android,IOS和Flutter之间进行通信,您可以检查以下网址。 https://medium.com/flutter/flutter-platform-channels-ce7f540a104e
new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
new MethodCallHandler() {
@Override
public void onMethodCall(MethodCall call, Result result) {
// Note: this method is invoked on the main thread.
// TODO
}
});