如何在 flutter 中明智地获取 SQFlite 数据日期?

How to get SQFlite data date wise in flutter?

我正在用 flutter 创建待办事项应用程序。我需要明智地显示 Todos 日期。就像今天创建的所有 Todos 都应该显示在 Today 下一样,所有明天的 Todos 都应该显示在 Tomorrow 下。

我是这样创建我的 table 的:

database.execute("""
          CREATE TABLE Todotable(
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            taskName TEXT NOT NULL,
            taskTag TEXT NOT NULL,
            date TEXT NOT NULL,
            isReminder INTEGER NOT NULL,
            isCompleted INTEGER NOT NULL
          )
     """);

我不知道如何明智地查询 SQFlite 数据并将其格式化为 今天明天。并在今天和明天的部分显示,如设计所示。

感谢您的回答:)

获取明天的待办事项

//for tomorrow
           String tomorrowDate=  DateTime.now().add(Duration(days: 1)).toIso8601String();
              var todosForTomrrow= await database
                        .rawQuery('SELECT * FROM Todotable WHERE date = ?', [tomorrowDate]);
    //for today
               String todayDate=  DateTime.now().toIso8601String();
              var todosForToday= await database
                        .rawQuery('SELECT * FROM Todotable WHERE date = ?', [todayDate]);

日期已转换并以字符串格式保存在此处,并且在插入 table 之前应将日期转换为相同的格式

您可以在 sqflite 中创建 DATETIME 列。 这是在 sqflite 数据库 中创建的 Weather table 的示例:

batch.execute('''
CREATE TABLE $tableWeather (
$weatherLocalization TEXT NOT NULL,
$weatherDate DATETIME NOT NULL,
$weatherHumidityPercentage REAL,
$weatherWindDegree REAL,
$weatherWindSpeed REAL,
$weatherPressureHPascal INTEGER,
$weatherTemperatureCelsius REAL,
$weatherDescription TEXT,
$weatherIconId TEXT,
PRIMARY KEY($weatherLocalization, $weatherDate));
''',);

您可以创建一个 Weather 对象,如下所示:

class Weather{
      String localization;
      DateTime date;
      double humidityPercentage;
      double windDegree;
      double windSpeedMS;
      int pressureHPascal;
      double temperatureCelsius;
      String description;
      String iconId;

  Weather({
    @required this.localization,
    @required this.date,
    this.humidityPercentage,
    this.windDegree,
    this.windSpeedMS,
    this.pressureHPascal,
    this.temperatureCelsius,
    this.description,
    this.iconId
  });

  //to be used when inserting a row in the table
  Map<String, dynamic> toMap() {
    final map = new Map<String, dynamic>();
    map["$weatherLocalization"] = localization;
    map["$weatherDate"] = date.toString();
    map["$weatherHumidityPercentage"] = humidityPercentage;
    map["$weatherWindDegree"] = windDegree;
    map["$weatherWindSpeed"] = windSpeedMS;
    map["$weatherPressureHPascal"] = pressureHPascal;
    map["$weatherTemperatureCelsius"] = temperatureCelsius;
    map["$weatherDescription"] = description;
    map["$weatherIconId"] = iconId;
    return map;
  }

  //to be used when converting the row into object
  factory WeatherOnDate.fromMap(Map<String, dynamic> data) => new WeatherOnDate(
      localization: data["$weatherLocalization"],
      date: DateTime.parse(data["$weatherDate"]),
      humidityPercentage: data["$weatherHumidityPercentage"],
      windDegree: data["$weatherWindDegree"],
      windSpeedMS: data["$weatherWindSpeed"],
      pressureHPascal: data["$weatherPressureHPascal"],
      temperatureCelsius: data["$weatherTemperatureCelsius"],
      description: data["$weatherDescription"],
      iconId: data["$weatherIconId"]
  );
}

小心地将您的 DateTime 属性转换为字符串或 int,就像我在 toMap() 函数中所做的那样。

然后,当你想获取一个日期时,你可以这样做:

Future<Weather> fetchWeatherOnDate(DateTime dateTime) async {
  DatabaseHelper _databaseHelper = Injection.injector.get();
  List<Map<String, dynamic>> weatherMaps = await _databaseHelper.db.rawQuery(
      'SELECT * FROM $tableWeather WHERE DATE($weatherDate) = DATE(?)',
      [dateTime.toString()]);

  List<Weather> weathers= [];
  for (final weatherMap in weatherMaps) {
    weathers.add(Weather.fromMap(weatherMap));
  }
  if (weathers.isNotEmpty){
    return weathers[0];
  }
  return null;
}

DateTime today = DateTime.now()
Weather weatherToday = fetchWeatherOnDate(today);

我认为它可以让您很好地了解如何解决您的问题:)

Flutter SQLite 包不支持 DateTime。 检查有关支持的 SQLite 类型的信息: https://pub.dev/packages/sqflite#supported-sqlite-types

DateTime is not a supported SQLite type. Personally I store them as int (millisSinceEpoch) or string (iso8601)

我们可以按照包开发人员的建议使用 String 或 int。 要在数据库中有条件地选择当天的项目,也许字符串更方便。

个人比较喜欢用user formatter来获取搜索关键词,如下图:

    DateFormat formater = DateFormat('yyyyMMdd');
    var today = formater.format(DateTime.now());
    var tomorrow = formater.format(DateTime.now().add(const Duration(days: 1)));

要在数据库中搜索,我会使用如下方法:

Future<TodoList?> getTodoListByDay(String day) async {
    final db = await database;
    String sql =
        "SELECT * FROM Todotable WHERE date = \'${day}\' ";
    var res = await db.rawQuery(sql);
    List<TodoList> objs = res.isNotEmpty
        ? res.map((c) => TodoList.fromMap(c)).toList()
        : [];

    return objs.isNotEmpty ? objs : null;
}

TodoList class 可以从 json 生成,就像我使用 'jsonToDartModel' 包一样。

import 'dart:convert';

class TodoList {
  int? id;
  String? taskName;
  String? taskTag;
  String? date;
  int? isReminder;
  int? isCompleted;

  TodoList({
    this.id,
    this.taskName,
    this.taskTag,
    this.date,
    this.isReminder,
    this.isCompleted,
  });

  factory TodoList.fromMap(Map<String, dynamic> data) => TodoList(
        id: data['id'] as int?,
        taskName: data['taskName'] as String?,
        taskTag: data['taskTag'] as String?,
        date: data['date'] as String?,
        isReminder: data['isReminder'] as int?,
        isCompleted: data['isCompleted'] as int?,
      );

  Map<String, dynamic> toMap() => {
        'id': id,
        'taskName': taskName,
        'taskTag': taskTag,
        'date': date,
        'isReminder': isReminder,
        'isCompleted': isCompleted,
      };

  /// `dart:convert`
  ///
  /// Parses the string and returns the resulting Json object as [TodoList].
  factory TodoList.fromJson(String data) {
    return TodoList.fromMap(json.decode(data) as Map<String, dynamic>);
  }

  /// `dart:convert`
  ///
  /// Converts [TodoList] to a JSON string.
  String toJson() => json.encode(toMap());
}