LoginSignup
0
0

【Flutter】スワイプでリストから項目を消す

Last updated at Posted at 2023-12-17

Dismissible ウィジェットを使用するとスワイプで削除できる。

Dismissible ウィジェット とは

指定方向にスワイプすると子要素が消えるウィジェット。

サンプルソース

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: TodoList(),
    );
  }
}

class TodoList extends StatefulWidget {
  @override
  _TodoListState createState() => _TodoListState();
}

class _TodoListState extends State<TodoList> {
  List<String> todoItems = ["Task 1", "Task 2", "Task 3"];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Todo List"),
      ),
      body: ListView.builder(
        itemCount: todoItems.length,
        itemBuilder: (context, index) {
          final todoItem = todoItems[index];
          return Dismissible( // ここでDismissibleウィジェットを使用
            key: Key(todoItem),
            background: Container( // スワイプしたときに後ろに見える背景
              color: Colors.red,
              alignment: Alignment.centerRight, // text-align: right; と一緒
              padding: EdgeInsets.symmetric(horizontal: 20.0),
              child: Icon(
                Icons.delete,
                color: Colors.white,
              ),
            ),
            onDismissed: (direction) { // 削除されるときに実行される
              // アイテムを削除
              setState(() {
                todoItems.removeAt(index);
              });
              // スナックバーを表示
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(
                  content: Text('$todoItem を削除しました'),
                ),
              );
            },
            child: ListTile(
              title: Text(todoItem),
            ),
          );
        },
      ),
    );
  }
}

感想

もっと複雑な構造かと思った。

参考

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