I'm having problem with foreign key while adding a new habit and inserting it's data in db and I don't really know why, because everything seems right. the error is:

[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: DatabaseException(FOREIGN KEY constraint failed (code 787)) sql 'INSERT OR FAIL INTO Habits (userId, text, emoji, period, startPeriod) VALUES (?, ?, ?, ?, NULL)' args [1, habit, ☺, [1,2,3,4,5,6,7]]

error accrued here:

class DataService {...
  late final Database db;
    Future<void> addHabit(Habit newHabit) async {
        final newHabitId = await HabitsDb.createHabit(db, newHabit);//error accrued here
        final days = (await HabitsDb.getAllDays(db)).map((e) => Day.fromDb(e, []));

        for (final day in days) {
          if (newHabit.startPeriod != null &&
              newHabit.startPeriod!.compareTo(day.date) > 0) {
            continue;
          }

          if (newHabit.period.contains(day.date.weekday)) {
            await HabitsDb.createHabitDay(
                db, day.date.millisecondsSinceEpoch, newHabitId);
          }
        }

        await _reloadDaysInCache();
        _loadHabits();
      } ...}

then:

class HabitsDb{...
  static Future<int> createHabit(Database db, Habit habit) async {
    return db.insert(HabitsTable.tableName, await habit.toDb(),
        conflictAlgorithm: ConflictAlgorithm.fail);
  }...}

model:

    class Habit {
      late final int id;
      late final int userId;
      late String text;
      late String emoji;
      late final List<int> period;
      late final DateTime? startPeriod;
...
    Future<Map<String, dynamic>> toDb() async {

        print(text);
        print(userId);
        return {
          //HabitsTable.id: id,
          HabitsTable.userId: userId,
          HabitsTable.text: text,
          HabitsTable.emoji: emoji,
          HabitsTable.period: jsonEncode(period),
          HabitsTable.startPeriod: startPeriod?.millisecondsSinceEpoch
        };
      }...}

creating table:

class HabitsTable {
  static const String tableName = 'Habits';

  static const String id = 'id';
  static const String userId = 'userId';
  static const String text = 'text';
  static const String emoji = 'emoji';
  static const String period = 'period';
  static const String startPeriod = 'startPeriod';

  static const String createQuery = '''
    CREATE TABLE IF NOT EXISTS $tableName (
      $id INTEGER PRIMARY KEY AUTOINCREMENT,
      $userId INTEGER NOT NULL,
      $text TEXT NOT NULL,
      $emoji TEXT NOT NULL,
      $period TEXT NOT NULL,
      $startPeriod INTEGER,
      FOREIGN KEY($userId) REFERENCES ${UsersTable.tableName}(id));''';
}

if more code is needed you can check https://github.com/sarasoltan/habit_tracker plz help if you know how to solve this error.