どうも、ちょげ(@chogetarou)です。
AlertDialogを自動で閉じる方法を紹介します。
方法

AlertDialogを自動で閉じるには、「Timer」を使います。
まず、Timerを使うために「dart:async」をインポートします。
import 'dart:async';
そして、Timer用の変数を用意します。
Timer? _timer;
次に、「showDialog」を表示する前に、タイマーで時間をセットします。
また、第2引数で時間が経った後に「Navigator.pop(context)」が呼び出されるようにします。
_timer = Timer(
Duration(seconds: 3),//閉じる時間(ここは皆さんで調整してください)
() {
Navigator.pop(context); //時間が経った後の処理
},
);
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Alert'),
);
},
);
最後に、showDialogに「await」を付与します。
_timer = Timer(
Duration(seconds: 3),
() {
Navigator.pop(context);
},
);
await showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Alert'),
);
},
);
また、showDialogの後に「Timer」のインスタンスを破棄しなければいけません。
_timer = Timer(
Duration(seconds: 3),
() {
Navigator.pop(context);
},
);
await showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Alert'),
);
},
);
if (_timer != null && _timer!.isActive) {
_timer!.cancel();
}
これでアラートが自動的に閉じられるようになります。
以下は、使用例です。
Timer? _timer;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ElevatedButton(
onPressed: () async {
_timer = Timer(
Duration(seconds: 3),
() {
Navigator.pop(context);
},
);
await showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Alert'),
);
},
);
if (_timer != null && _timer!.isActive) {
_timer!.cancel();
}
},
child: Text('Button'),
)
],
),
),
);
}
コメント