Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

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.

@gi-ra-ffeAdvent Calendar 2023

Day 18

【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

Comments

No comments

Let's comment your feelings that are more than good

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?

Login to continue?

Login or Sign up with social account

Login or Sign up with your email address