2017-06-19 73 views
1

我需要在用戶通過Android設備上的Back按鈕導航離開當前路由之前顯示警告對話框。我試圖通過在widget狀態下實現WidgetsBindingObserver來攔截按鈕行爲。 GitHub上有關於相同主題的關閉issue。然而,我的代碼不工作,因爲方法didPopRoute()從未被調用。這裏是我下面的代碼: 有沒有什麼方法在Android上Flutter應用中攔截'返回'keydown?

import 'dart:async'; 

import 'package:flutter/material.dart'; 

class NewEntry extends StatefulWidget { 
    NewEntry({Key key, this.title}) :super(key: key); 

    final String title; 

    @override 
    State<StatefulWidget> createState() => new _NewEntryState(); 
} 

class _NewEntryState extends State<NewEntry> with WidgetsBindingObserver { 
    @override 
    void initState() { 
    super.initState(); 
    WidgetsBinding.instance.addObserver(this); 
    } 

    @override 
    void dispose() { 
    WidgetsBinding.instance.removeObserver(this); 
    super.dispose(); 
    } 

    @override 
    Future<bool> didPopRoute() { 
    return showDialog(
     context: context, 
     child: new AlertDialog(
     title: new Text('Are you sure?'), 
     content: new Text('Unsaved data will be lost.'), 
     actions: <Widget>[ 
      new FlatButton(
      onPressed:() => Navigator.of(context).pop(true), 
      child: new Text('No'), 
     ), 
      new FlatButton(
      onPressed:() => Navigator.of(context).pop(false), 
      child: new Text('Yes'), 
     ), 
     ], 
    ), 
    ); 
    } 

    @override 
    Widget build(BuildContext context) { 
    return new Scaffold(
     appBar: new AppBar(
     title: new Text(widget.title), 
    ), 
     floatingActionButton: new FloatingActionButton(
     child: new Icon(Icons.edit), 
     onPressed:() {}, 
    ), 
    ); 
    } 
} 

回答

2

我找到了解決辦法是使用WillPopScope部件。以下是最終代碼:

import 'dart:async'; 

import 'package:flutter/material.dart'; 

class NewEntry extends StatefulWidget { 
    NewEntry({Key key, this.title}) :super(key: key); 

    final String title; 

    @override 
    State<StatefulWidget> createState() => new _NewEntryState(); 
} 

class _NewEntryState extends State<NewEntry> { 

    Future<bool> _onWillPop() { 
    return showDialog(
     context: context, 
     child: new AlertDialog(
     title: new Text('Are you sure?'), 
     content: new Text('Unsaved data will be lost.'), 
     actions: <Widget>[ 
      new FlatButton(
      onPressed:() => Navigator.of(context).pop(false), 
      child: new Text('No'), 
     ), 
      new FlatButton(
      onPressed:() => Navigator.of(context).pop(true), 
      child: new Text('Yes'), 
     ), 
     ], 
    ), 
    ) ?? false; 
    } 

    @override 
    Widget build(BuildContext context) { 
    return new WillPopScope(
     onWillPop: _onWillPop, 
     child: new Scaffold(
     appBar: new AppBar(
      title: new Text(widget.title), 
     ), 
     floatingActionButton: new FloatingActionButton(
      child: new Icon(Icons.edit), 
      onPressed:() {}, 
     ), 
    ), 
    ); 
    } 
}