0
0

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でDismissible(スワイプして消す)とshowDialog(アラート確認)を組み合わせて実装する方法

Posted at

ダイアログイメージ

スクリーンショット 2023-04-23 8.07.21.png

該当部分の抜粋

return Dismissible(
  key: Key(item), // アイテムごとに一意のキーを設定する
  onDismissed: (direction) { // スワイプでアイテムが削除されたときの処理
    setState(() {
      items.removeAt(index); // リストからアイテムを削除する
    });

    ScaffoldMessenger.of(context).showSnackBar(SnackBar( // 削除されたことを示すスナックバーを表示する
      content: Text("$item dismissed"),
    ));
  },
  confirmDismiss: (direction) async { // アイテムを削除する前に確認ダイアログを表示する
    return await showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text("Confirm"), // ダイアログのタイトル
          content: Text("Are you sure you wish to delete this item?"), // ダイアログのメッセージ
          actions: <Widget>[
            TextButton(
              onPressed: () => Navigator.of(context).pop(false), // キャンセルボタンを押したときの処理
              child: Text("CANCEL"),
            ),
            TextButton(
              onPressed: () => Navigator.of(context).pop(true), // 削除ボタンを押したときの処理
              child: Text("DELETE"),
            ),
          ],
        );
      },
    );
  },
);

全体

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final items = List<String>.generate(20, (i) => "Item ${i + 1}");

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: ListView.builder(
        itemCount: items.length,
        itemBuilder: (context, index) {
          final item = items[index];

          return Dismissible(
            key: Key(item),
            onDismissed: (direction) {
              setState(() {
                items.removeAt(index);
              });

              ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                content: Text("$item dismissed"),
              ));
            },
            confirmDismiss: (direction) async {
              return await showDialog(
                context: context,
                builder: (BuildContext context) {
                  return AlertDialog(
                    title: Text("Confirm"),
                    content: Text("Are you sure you wish to delete this item?"),
                    actions: <Widget>[
                      TextButton(
                          onPressed: () => Navigator.of(context).pop(false),
                          child: Text("CANCEL")),
                      TextButton(
                          onPressed: () => Navigator.of(context).pop(true),
                          child: Text("DELETE")),
                    ],
                  );
                },
              );
            },
            background: Container(
              color: Colors.red,
              child: Icon(Icons.delete),
              alignment: Alignment.centerRight,
              padding: EdgeInsets.only(right: 20),
            ),
            child: ListTile(
              title: Text('$item'),
            ),
          );
        },
      ),
    );
  }
}

最初はonDismissedの中でダイアログを呼ぶ感じでやってみたんですが、CANCELを押してもリストが消えてしまうという問題があり、いろいろ試したんですが、改善できず。

これじゃあかんかって思ってググったらこうすればいけるよって書いてあったのでそちらを参考にしました。

またListView.builderとDismissibleとshowDialogを使った日本語の記事がほぼなかったこともあり、せっかくなので投稿しました。

どなたかの参考になれば幸いです。スクリーンショット 2023-04-23 8.06.54.png

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?