flutter捕獲應用退出彈出對話框


 

使用WillPopScope組件,它會檢測到子組件的Navigation的pop事件,並攔截下來。我們需要在它的onWillPop屬性中返回一個新的組件(一般是一個Dialog)處理是否真的pop該頁面。

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

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

class _HomePageState extends State<HomePage> {

    Future<bool> _onBackPressed() {
        return showDialog(
            context: context,
            builder: (context) =>
                AlertDialog(
                    title: Text('確定退出程序嗎?'),
                    actions: <Widget>[
                        FlatButton(
                            child: Text('暫不'),
                            onPressed: () => Navigator.pop(context, false),
                        ),
                        FlatButton(
                            child: Text('確定'),
                            onPressed: () => Navigator.pop(context, true),
                        ),
                    ],
                ));
    }

    @override
    Widget build(BuildContext context) {
        return WillPopScope(
            onWillPop: _onBackPressed,
            child: Scaffold(
                appBar: AppBar(
                    title: Text('title'),
                ),
                body: Center(
                    child: Text('exit'),
                ),
            ),
        );
    }
}

這里有另外一種情況就是,當我們填寫一些表單時,如果沒填完畢就直接想要退出,這時也需要用到彈窗警告是否確定退出,這種情況form widget就直接提供了這個屬性,使用方法跟上面一樣;

 new Form(
       onWillPop: _onBackPressed,
       key: _formKey,
       autovalidate: true,
    child:。。。。
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM