颤动:如何在按下后退按钮时不退出应用程序

Ayu*_*har 7 flutter flutter-navigation

应用程序的通常行为是在按下后退按钮时退出。我想要的是当按下后退按钮时,应用程序在不退出的情况下进入后台。就像我们从一个应用程序切换到另一个应用程序时会发生什么一样。

我知道这将涉及使用WillPopScope()但如何处理onBackPressed事件以将应用程序保持在后台,而不是退出。

Yas*_*ain -1

尝试下面的代码它会起作用:

代码:

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"),
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)