【问题标题】:Connecting a Calendar with a Database将日历与数据库连接
【发布时间】:2020-03-19 17:26:13
【问题描述】:

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

为此,我选择了 sqflite 包和 flutter_bloc。这里有一个很棒的教程:Database Storage in Flutter using Sqflite

数据库使用 List 数据结构,而日历使用 Map>

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

  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


    【解决方案1】:

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

    我现在将在数据库中找到的行的 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-18
      • 2011-07-23
      • 1970-01-01
      • 2016-08-30
      • 2014-10-31
      • 2019-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多