はじめに
FlutterのAlertDialog
を共通のwidgetとして、複数の所で使いたいと言う場合はよくあるかと思います。
そんな時、「キャンセル」は閉じる、「OK」なら任意の処理を発動すると言う実装はどうやったらいいのだろう?と思い調べてみました!
何かしらの情報を表示させるだけのAlertDialog
なら簡単にできるんですけど、、、
共通化したAlertDialogにFunctionを渡す
共通化したAlertDialog
import 'package:flutter/material.dart';
class ConfirmationDialog extends StatelessWidget {
const ConfirmationDialog({
Key? key,
required this.action,
}) : super(key: key);
final Function? action;
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text(
'AlertDialog Title',
style: Theme.of(context).textTheme.headline6,
),
content: Text('AlertDialog description',
style: Theme.of(context).textTheme.bodyText1),
actions: <Widget>[
TextButton(
onPressed: () => Navigator.pop(context, 'Cancel'),
child: const Text('Cancel'),
),
TextButton(
onPressed: () {
Navigator.pop(context, 'OK');
print('送信だ!!!');
action!(); // 渡された処理を実行
},
child: const Text('OK'),
),
],
);
}
}
使用例
void postTheme(String uid) async {
String res = await FireStoreMethods()
.postTheme(_titleController.text, _descriptionController.text, uid);
}
// 省略
final UserProvider userProvider = Provider.of<UserProvider>(context);
// 省略
TextButton(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: !_isLoading
? const Text('投稿')
: const CircularProgressIndicator(color: primaryColor),
),
onPressed: () => showDialog(
context: context,
builder: (context) => ConfirmationDialog(
action: () {
postTheme(userProvider.getUser.uid); // 引数に値をもたすことも可能!
},
),
),
style: TextButton.styleFrom(
backgroundColor: secondaryColor,
shape: const StadiumBorder(),
),
),
これで色々な処理を「OK」の場合に実行することができるようになりました!
よくあるエラー
This expression has a type of 'void' so its value can't be used. Try checking to see if you're using the correct API; there might be a function or call that returns void you didn't expect. Also check type parameters and variables which might also be void
👇これだとダメです!
onPressed: () => showDialog(
context: context,
builder: (context) => ConfirmationDialog(
action: postTheme(userProvider.getUser.uid),
),
),
actionはFunction
なので、() {}
の形にしてあげないといけません。