Click again to return flutter Andrews quit the application

Click on Android phones or virtual entity return key, will return to the previous level, when reaching the top is, Click Back to exit the application, in order to prevent the user clicks continuous returns, leading to withdraw the application, the user clicks on the return to the top, if the click again to reverse for the first time do not quit, and enhance the user clicks to exit again

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '',
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _onWillPop,
      child: Scaffold(
        appBar: AppBar(title: Text('data'),),
        body: Container(
        child: Center(child: Text('data')),
      ),
      )
    );
  }

  int last = 0;
  Future<bool> _onWillPop() {
    //计算两次时间间隔
    int now = DateTime.now().millisecondsSinceEpoch;
    if (now - last > 8000) {
      last = DateTime.now().millisecondsSinceEpoch;
      Fluttertoast.showToast(msg: '再次点击返回退出应用',gravity: ToastGravity.BOTTOM);
      return Future.value(false);
    } else {
      return Future.value(true);
    }
  }
}

Guess you like

Origin www.cnblogs.com/qqcc1388/p/11753417.html