使用滑动从数据库中删除项目 - Sqflite

delete item from database with swipe - Sqflite

我想实现一项功能,当我滑动列表项时,它会从数据库中删除该项目。我对滑动和删除部分使用了 dismisible,但我不知道如何从数据库中删除项目。这是我的数据库帮助文件:

import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:wodo/models/task.dart';

class DatabaseHelper {
  Future<Database> database() async {
    return openDatabase(
      join(await getDatabasesPath(), 'todo_database.db'),
      onCreate: (db, version) {
        return db.execute(
            "CREATE TABLE tasks(id INTEGER PRIMARY KEY, name TEXT, date TEXT)");
      },
      version: 1,
    );
  }

  Future<void> insertTask(Task task) async {
    Database _db = await database();
    await _db.insert('tasks', task.toMap(),
        conflictAlgorithm: ConflictAlgorithm.replace);
  }

  Future<List<Task>> getTasks() async {
    Database db = await database();
    List<Map<String, dynamic>> taskMap = await db.query('tasks');
    return List.generate(taskMap.length, (index) {
      return Task(
          id: taskMap[index]['id'],
          name: taskMap[index]['name'],
          date: taskMap[index]['date']);
    });
  }
}

要删除项目,只需使用 delete 方法。如 documentation

中所述
db.delete(TABLE_NAME, where: "id = ?", whereArgs: [id]);

以下是您可以为实际数据库端执行的操作:

Future<int> delete(int id) async {
    final db = await database;     // replacd with database instance

    return await db.delete(
      TABLE,     // replace with table name
      where: "id = ?",
      whereArgs: [id],   // you need the id
    );
  }

然后要实际更新您的屏幕,您需要执行以下操作:

    DatabaseProviderLog.db.delete(log.id).then((_){     // call this action
      BlocProvider.of<LogBloc>(context).add(
        DeleteLog(index), // uses Bloc Provider and an event to update screen
      );
    }

在单独文件中的事件:

    import 'package:FilamentLeft/models/profiles.dart';

    abstract class ProfileEvent {}



    class UpdateProfile extends ProfileEvent {
      Profile newProfile;
      int profileIndex;

      UpdateProfile(int index, Profile profile) {
        newProfile = profile;
        profileIndex = index;
      }
    }



    class SetProfiles extends ProfileEvent {
      List<Profile> profileList;

      SetProfiles(List<Profile> profiles) {
        profileList = profiles;
      }
    }




    class AddProfile extends ProfileEvent {
      Profile newProfile;

      AddProfile(Profile profile) {
        newProfile = profile;
      }
    }




    class DeleteProfile extends ProfileEvent {
      int profileIndex;

      DeleteProfile(int index) {
        profileIndex = index;
      }
    }