代码如下
flutter for 安卓 MainActivity代码如下
package com.flutter.study_app;
import android.os.Bundle;
import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugins.GeneratedPluginRegistrant;
public class MainActivity extends FlutterActivity {
private final String chanel = "android/back/desktop";
static final String eventBackDesktop = "backDesktop";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
initBackTop();
}
private void initBackTop() {
new MethodChannel(getFlutterView(), chanel).setMethodCallHandler(
(methodCall, result) -> {
if (methodCall.method.equals(eventBackDesktop)) {
moveTaskToBack(false);
result.success(true);
}
}
);
}
}
flutter代码
import 'package:flutter/services.dart';
import 'package:flutter/material.dart';
class AndroidBackTop {
static const String chanel = "android/back/desktop";
static const String eventBackDesktop = "backDesktop";
static Future<bool> backDesktop() async {
final platform = MethodChannel(chanel);
try {
await platform.invokeMethod(eventBackDesktop);
} on PlatformException catch (e) {
debugPrint(e.toString());
}
return Future.value(false);
}
}
使用示例
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:study_app/views/back_desktop/utils/android_back_desktop_util.dart';
class BackDesktop extends StatefulWidget {
final String title;
BackDesktop({Key key, this.title}) : super(key: key);
@override
_BackDesktopState createState() => new _BackDesktopState();
}
class _BackDesktopState extends State<BackDesktop> {
int _count = 0;
void _changeCount() {
setState(() {
_count++;
});
}
void _openPage1() {}
@override
void dispose() {
super.dispose();
}
@override
Widget build(BuildContext context) {
debugPrint('xxxx');
return WillPopScope(
onWillPop: AndroidBackTop.backDesktop,
child: new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text("点击按钮改变数字"),
new Text("数字" + _count.toString(), style: Theme.of(context).textTheme.display1),
new FlatButton(
onPressed: _openPage1,
child: Text('打开page1'),
color: Theme.of(context).textSelectionColor,
highlightColor: Color.fromRGBO(0, 0, 255, .5),
)
],
)),
floatingActionButton: new FloatingActionButton(
onPressed: _changeCount,
tooltip: '点我改变数字',
child: new Icon(Icons.add),
mini: true,
),
floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
));
}
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
home: new BackDesktop(
title: "计数器",
));
}
}