该应用程序的通常行为是,当按下后退按钮时退出。我想要的是让应用程序在按下后退按钮时进入后台而不退出。就像当我们从一个应用程序切换到另一个应用程序时会发生什么。
我知道这将涉及使用WillPopScope()
,但如何处理onBackPressed
事件以使应用程序保持后台运行,而不是退出该事件。
答案 0 :(得分:0)
尝试以下代码将起作用:
代码:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp((MainScreen()));
class MainScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: MyApp(),
);
}
}
class MyApp extends StatefulWidget {
MyApp({Key key}) : super(key: key);
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () => SystemChannels.platform.invokeMethod(
'SystemNavigator.pop'), // this is use to keep the app in background
child: Scaffold(
body: Center(
child: Text("Text"),
),
),
);
}
}
答案 1 :(得分:0)
Future<bool> _onBackpressed(){
SystemNavigator.pop();
return True;
}
WillPopScope(
onWillPop: _onBackpressed() ,
)