debugging 尝试创建SQLite创建数据库插入函数-未定义名称“”,尝试将名称更正为已定义的名称,或定义名称

cngwdvgl  于 2023-04-30  发布在  SQLite
关注(0)|答案(1)|浏览(153)

我是一个新的Flutter学习者谁目前正在学习通过视频https://www.youtube.com/watch?v=pQSTgf-6hDk&t=451s。我尝试定义createTask()函数,但它存在错误Undefined name ''从第43行开始,直到第64行。尝试将名称更正为已定义的名称,或定义名称。我已经在底部定义了名称,但它仍然显示消息红线,任何人都可以帮助我识别错误并提出解决它的建议。感谢你的帮助,谢谢。
下面是代码附件:

import 'package:flutter/material.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';

class DatabaseAlreadyOpenException implements Exception {}

class UnableToGetDocumentException implements Exception {}

class DatabaseIsNotOpenException implements Exception {}

class CouldNotDeleteUserException implements Exception {}

class UserAlreadyExistException implements Exception {}

class CouldNotFindUserException implements Exception {}

class TaskService {
  Database? _db;
  

  Database _getDatabaseOrThrow() {
    final db = _db;
    if (db == null) {
      throw DatabaseIsNotOpenException();
    } else {
      return db;
    }
  }

  Future<DatabaseTask> createTask({required DatabaseUser owner}) async {
    final db = _getDatabaseOrThrow();
    final dbUser = await getUser(email: owner.email);

    // make sure owner exists in the database with the correct id
    if (dbUser != owner) {
      throw CouldNotFindUserException();
    }

    // create the task
    final noteId = await db.insert(taskTable, {
      userIdColumn: owner.id,
      titleColumn: title,
      noteColumn: note, 
      isCompletedColumn: isCompleted, 
      dateColumn: date, 
      startTimeColumn: startTime,
      endTime: endTime, 
      color: color, 
      remind: remind, 
      repeat: repeat
    });

    final task = DatabaseTask(
    id: noteId, 
    userId: owner.id, 
    title: title, 
    note: note, 
    isCompleted: isCompleted, 
    date: date, 
    startTime: startTime, 
    endTime: endTime, 
    color: color, 
    remind: remind, 
    repeat: repeat,
    );
    return task;
  }

  Future<DatabaseUser> getUser({required String email}) async {
    final db = _getDatabaseOrThrow();

    final results = await db.query(
      userTable,
      limit: 1,
      where: 'email = ?',
      whereArgs: [email.toLowerCase()],
    );

    if (results.isEmpty) {
      throw CouldNotFindUserException();
    } else {
      return DatabaseUser.fromRow(results.first);
    }
  }

  Future<DatabaseUser> createUser({required String email}) async {
    final db = _getDatabaseOrThrow();
    final results = await db.query(userTable,
        limit: 1, where: 'email = ?', whereArgs: [email.toLowerCase()]);
    if (results.isNotEmpty) {
      throw UserAlreadyExistException();
    }
    final userId = await db.insert(userTable, {
      emailColumn: email.toLowerCase(),
    });
    return DatabaseUser(id: userId, email: email);
  }

   Future<void> deleteUser({required String email}) async {
     final db = _getDatabaseOrThrow();
     final deletedCount = await db.delete(
     userTable,
     where: 'email = ?',
     whereArgs: [email.toLowerCase()],
     );
     if(deletedCount != 1){
       throw CouldNotDeleteUserException();
     }
   }

  Future<void> close() async {
    final db = _db;
    if (db == null) {
      throw DatabaseIsNotOpenException();
    } else {
      await db.close();
      _db = null;
    }
  }

  Future<void> open() async {
    if (_db != null) {
      throw DatabaseAlreadyOpenException();
    }
    try {
      final docsPath = await getApplicationDocumentsDirectory();
      final dbPath = join(docsPath.path, dbName);
      final db = await openDatabase(dbPath);
      _db = db;

      await db.execute(createUserTable);

      await db.execute(createTaskTable);

    } on MissingPlatformDirectoryException {
      throw UnableToGetDocumentException();
    }
  }
}

@immutable
class DatabaseUser {
  final int id;
  final String email;

  const DatabaseUser({required this.id, required this.email});

  // read hash table for every row, every user inside the database represented by object of map of String and an optional object
  DatabaseUser.fromRow(Map<String, Object?> map)
      : id = map[idColumn] as int,
        email = map[emailColumn] as String;

  @override
  String toString() => 'Person, ID = $id, email = $email';

  @override
  bool operator ==(covariant DatabaseUser other) => id == other.id;

  // id is primary key of class
  @override
  int get hashCode => id.hashCode;
}

class DatabaseTask {
  final int id;
  final int userId;
  final String title;
  final String note;
  final int isCompleted;
  final String date;
  final String startTime;
  final String endTime;
  final int color;
  final int remind;
  final String repeat;

  DatabaseTask(
      {required this.id,
      required this.userId,
      required this.title,
      required this.note,
      required this.isCompleted,
      required this.date,
      required this.startTime,
      required this.endTime,
      required this.color,
      required this.remind,
      required this.repeat});

  DatabaseTask.fromRow(Map<String, Object?> map)
      : id = map[idColumn] as int,
        userId = map[userIdColumn] as int,
        title = map[titleColumn] as String,
        note = map[noteColumn] as String,
        isCompleted = map[isCompletedColumn] as int,
        date = map[dateColumn] as String,
        startTime = map[startTimeColumn] as String,
        endTime = map[endTimeColumn] as String,
        color = map[colorColumn] as int,
        remind = map[remindColumn] as int,
        repeat = map[repeatColumn] as String;

  @override
  String toString() =>
      'Task, ID = $id, userID =$userId , title = $title, note = $note, isCompleted = $isCompleted, date = $date, startDate = $startTime, endTime = $endTime, color = $color, remind = $remind, repeat = $repeat';

  @override
  bool operator ==(covariant DatabaseTask other) => id == other.id;

  // id is primary key of class
  @override
  int get hashCode => id.hashCode;
}

const dbName = 'tasks.db';
const taskTable = 'task';
const userTable = 'user';
const idColumn = 'id';
const emailColumn = 'email';
const userIdColumn = 'user_id';
const titleColumn = 'title';
const noteColumn = 'note';
const isCompletedColumn = 'isCompleted';
const dateColumn = 'date';
const startTimeColumn = 'startTime';
const endTimeColumn = 'endTime';
const colorColumn = 'color';
const remindColumn = 'remind';
const repeatColumn = 'repeat';
 const createUserTable = ''' CREATE TABLE IF NOT EXISTS "user" (
        "id"    INTEGER NOT NULL,
        "email" STRING NOT NULL UNIQUE,
        PRIMARY KEY("id" AUTOINCREMENT)
      );
      ''';
  const createTaskTable = ''' CREATE TABLE IF NOT EXISTS "tasks" (
        "id"    INTEGER NOT NULL,
        "user_id"   INTEGER NOT NULL,
        "title" STRING,
        "note"  STRING,
        "isCompleted"   INTEGER,
        "date"  STRING,
        "startTime" STRING,
        "endTime"   STRING,
        "color" INTEGER,
        "remind"    INTEGER,
        "repeat"    STRING,
        FOREIGN KEY("user_id") REFERENCES "user"("id"),
        PRIMARY KEY("id" AUTOINCREMENT)
      );
      ''';

enter image description hereenter image description here
我试着重写,但结果还是一样。只有当你写回之前定义的相同名称时,红线才会消失(E。g. title列:title列,注意列:noteColumn,)。请帮我调试错误并提供解决方案给我。谢谢!enter image description here

9rygscc1

9rygscc11#

这些属性不在类TaskService中定义,它们在类DatabaseTask中定义
你也可以在TaskService中定义它们,或者在createTask方法中将其作为参数。但是无论如何,您需要在某个地方设置值,以便在insert语句和DatabaseTask构造函数中设置值。

相关问题