Flutter組件學習(22)導航返回攔截(WillPopScope)

簡介

Flutter中可以通過WillPopScope來實現返回按鈕攔截

onWillPop是一個WillPopScope的回調函數,當用戶點擊返回按鈕時被調用

WillPopScope必須包含child,否則會報錯

實現雙擊返退出APP

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return WillPopTest();
  }
}

class WillPopTest extends State {
  DateTime _lastTime;
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.blue,
          centerTitle: true,
          title: Text(
            '實現二次點擊退出',
            style: TextStyle(fontSize: 18, color: Colors.white),
          ),
        ),
        body: WillPopScope(
          onWillPop: ()async{
            if(_lastTime==null||DateTime.now().difference(_lastTime)>Duration(seconds: 1)){
              _lastTime=DateTime.now();
              Fluttertoast.showToast(msg: "再點擊一次退出app",
                fontSize: 16,
                backgroundColor: Colors.blue,
                textColor: Colors.white
              );
              return false;
            }
            return true;
          },
          child: Container(
            alignment: Alignment.center,
            child: Text(
              "1秒內連續按兩次返回鍵退出",
              style: TextStyle(fontSize: 30),
            ),
          ),
        ),
      ),
    );
  }
}

運行效果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章