首页 > 解决方案 > 将日历与数据库连接

问题描述

我正在使用颤振包table_calendar并希望将其事件与数据库连接起来。

为此,我选择了sqflite包和flutter_bloc。这里有一个很棒的教程:使用 Sqflite 在 Flutter 中存储数据库

数据库使用List数据结构,但日历使用Map< DateTime, List< dynamic>>

我编写了一个方法,它将数据库列表中找到的一天中的每个事件写入地图中,以便在 UI 中显示所有内容。正则表达式就在那里,因为我将日期保存为数据库中的文本并用点分隔。

  void shiftListToCustomEventsMap(List<Shift> shiftList) {
    for (int i = 0; i < shiftList.length; i++) {
      Shift shift = shiftList[i];
      String helpStringForDate = shift.dateOfShiftString;
      RegExp exp = new RegExp(r'(\d+)');
      Iterable<RegExpMatch> matches = exp.allMatches(helpStringForDate);
      int date = int.parse(matches.elementAt(0).group(0));
      int month = int.parse(matches.elementAt(1).group(0));
      int year = int.parse(matches.elementAt(2).group(0));
      DateTime shiftDateTime = new DateTime.utc(year, month, date, 12);

      if (customEvents[shiftDateTime] == null) {
        // creating a new List and passing a widget
        customEvents[shiftDateTime] = [_buildShiftContainer(shift: shift)];
      } else {
        List<dynamic> helpList = customEvents[shiftDateTime];
        helpList.add(_buildShiftContainer(shift: shift));
      }
    }
  }

因此,我使用两种数据结构来处理数据,这是次优的。

当我想从日历中删除事件时,问题就开始了。

问题:

如果我使用索引删除一天中的第二个事件,则该事件会在Map中按照我的意愿被删除,但在Database中,它会占用第二个实体并将其删除。

次优解决方案:

解决它的一种方法是在数据库中为每个日期创建一个新表,但我不确定这是解决它的最佳方法。

标签: flutter

解决方案


我找到了解决我的问题的方法。

我现在将在数据库中找到的行的 ID 保存在我的 Shift 对象中。我将此对象传递给一个方法来创建一个小部件,然后在 ListView.builder 中将其用作日历事件。

现在,当尝试删除日历事件时,我检索了小部件的全部信息。在这个小部件中,我保存了数据库中等效事件的 ID 位置。然后我通过这个 id 从数据库中删除该行。

以下代码是建议解决方案的一部分:

Shift deleteShift =
    getParametersFromWidgetInTheList(
        index: index);
// remove from database
DatabaseProvider.db
    .delete(deleteShift.id)
    .then((_) => BlocProvider.of<ShiftBloc>(
            context)
        .add(DeleteShift(deleteShift.id)));
// remove from customEvents Map
customEvents[_controller.selectedDay]
    .removeAt(index);

推荐阅读