1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Flutter】共通化したAlertDialogに「OK」の場合に実行する処理を渡す方法

Last updated at Posted at 2022-05-26

はじめに

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」の場合に実行することができるようになりました!:relieved:

よくあるエラー

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なので、() {}の形にしてあげないといけません。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?