2017-06-19 10 views
1

AndroidデバイスでBackボタンを押すと、ユーザーが現在のルートからナビゲートする前に警告ダイアログを表示する必要があります。ウィジェット状態でWidgetsBindingObserverを実装して、ボタンの動作を傍受しようとしました。同じトピックに関してGitHubに閉じられたissueがあります。しかし、私のコードはメソッドdidPopRoute()が呼び出されていないので動作しません。ここでは以下の私のコードは次のとおりです。 AndroidのFlutterアプリで「戻る」キーを傍受する方法はありますか?

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:() {}, 
     ), 
    ), 
    ); 
    } 
} 
関連する問題