どうも、ちょげ(@chogetarou)です。
AlertDialogで値を返す方法を紹介します。
方法

AlertDialogで値を返すには、「pop」メソッドを使います。
具体的には、「pop」メソッドの第2引数に返したい値を指定します。
AlertDialog(
title: Text('Alert'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, 'Hello'), //Helloを返す
child: Text('閉じる'),
)
],
),
もし、「showDialog」と一緒に使うならば、「async」と「await」を使います。
また、showDialog<T>のように戻り値の指定もします。
ElevatedButton(
onPressed: () async {
_alertText = await showDialog<String>(
context: context,
builder: (BuildContext context) => AlertDialog(
title: Text('Alert'),
actions: [
TextButton(
onPressed: () {
setState(() {
Navigator.pop(context, 'Hello');
});
},
child: Text('閉じる'),
)
],
),
);
},
child: Text('Button'),
)
popメソッドの戻り値とshowDialog<String>の「String」の部分は、皆さんで書き換えてください。
以下は、簡単な使用例です。
String? _alertText = '';
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(_alertText!),
ElevatedButton(
onPressed: () async {
_alertText = await showDialog<String>(
context: context,
builder: (BuildContext context) => AlertDialog(
title: Text('Alert'),
actions: [
TextButton(
onPressed: () {
setState(() {
Navigator.pop(context, 'Hello');
});
},
child: Text('閉じる'),
)
],
),
);
},
child: Text('Button'),
)
],
),
),
);
}
コメント