ホーム ウィジェットで、ユーザーがシステムの戻るボタンをタップすると、「アプリを終了しますか?」と尋ねる確認ダイアログを表示します。
システムの戻るボタンをどのように上書きまたは処理すればよいのかわかりません。
ベストアンサー1
使用できますWillPopScope
これを達成するために。
例:
import 'dart:async';
import 'package:flutter/material.dart';
class HomePage extends StatefulWidget {
HomePage({Key key, this.title}) :super(key: key);
final String title;
@override
State<StatefulWidget> createState() => new _HomePageState();
}
class _HomePageState extends State<HomePage> {
Future<bool> _onWillPop() async {
return (await showDialog(
context: context,
builder: (context) => new AlertDialog(
title: new Text('Are you sure?'),
content: new Text('Do you want to exit an App'),
actions: <Widget>[
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: new Text('No'),
),
TextButton(
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("Home Page"),
),
body: new Center(
child: new Text("Home Page"),
),
),
);
}
}
のチェック??-operator
についてはnull
、ここダイアログの外側をクリックすると showDialog が返されnull
、この場合は false が返されるため、これは重要です。