Flutter Sqflite:在空值上使用了空检查运算符

huangapple go评论66阅读模式
英文:

Flutter Sqflite : null check operator used on a null value

问题

我正在尝试使用Flutter和sqflite创建任务列表应用程序。我的表格已创建并在模拟器上正常显示,但是当我尝试在真实设备上测试我的应用程序时,我在点击"创建任务"按钮后会出现以下错误:在空值上使用了空检查运算符

请帮助我找到正确的解决方案。

这是我的 db_helper.dart 代码:

我在以下这行代码上遇到了错误: return await _db!.query(_tableName);

class DBHelper {
  static Database? _db;
  static final int _version = 1;
  static final String _tableName = "tasks";

  static Future<void> initDb() async {
    if (_db != null) {
      return;
    }
    try {
      String _path = await getDatabasesPath() + 'tasks.db';
      _db =
          await openDatabase(_path, version: _version, onCreate: (db, version) {
        print("Creating A New One");
        return db.execute("CREATE TABLE $_tableName("
            "id INTEGER PRIMARY KEY AUTOINCREMENT, "
            "title STRING, note TEXT, date STRING, "
            "startTime STRING, endTime STRING, "
            "remind INTEGER, repeat STRING, "
            "color INTEGER, "
            "isCompleted INTEGER)");
      });
    } catch (e) {
      print(e);
    }
  }

  static Future<int> insert(Task? task) async {
    print("Insert Function Called");
    return await _db?.insert(_tableName, task!.toJson()) ?? 1;
  }

  static Future<List<Map<String, dynamic>>> query() async {
    print("Query Function Called");
    return await _db!.query(_tableName); // --> **这里是我遇到错误的地方**
  }
}

这是我的 task_controller.dart 代码:

class TaskController extends GetxController {
  @override
  void onReady() {
    super.onReady();
  }

  var taskList = <Task>[].obs;

  Future<int> addTask({Task? task}) async {
    return await DBHelper.insert(task);
  }

  // 从表格获取数据
  void getTasks() async {
    List<Map<String, dynamic>> tasks = await DBHelper.query();
    taskList.assignAll(tasks.map((data) => new Task.fromJson(data)).toList());
  }
}

这是我的 home_page.dart 文件的一部分:

_showTasks() {
    return Expanded(
      child: Obx(() {
        return ListView.builder(
            itemCount: _taskController.taskList.length,
            itemBuilder: (_, index) {
              return Container(
                width: 100,
                height: 50,
                color: Colors.green,
                margin: const EdgeInsets.only(bottom: 10),
                child: Text(
                  _taskController.taskList[index].title.toString(),
                ),
              );
            });
      }),
    );
  }
}
英文:

I am trying to create a Task List app with Flutter and sqflite. My table is created and displays well on an Emulator but as soon I as try to test my app on a real device I get the following error: null check operator used on a null value after I try to to on the create task button.

Please help me with a proper solution.

This is my db_helper.dart Code:

I am getting the error on the Line: return await _db!.query(_tableName);

class DBHelper {
  static Database? _db;
  static final int _version = 1;
  static final String _tableName = &quot;tasks&quot;;

  static Future&lt;void&gt; initDb() async {
    if (_db != null) {
      return;
    }
    try {
      String _path = await getDatabasesPath() + &#39;tasks.db&#39;;
      _db =
          await openDatabase(_path, version: _version, onCreate: (db, version) {
        print(&quot;Creating A New One&quot;);
        return db.execute(&quot;CREATE TABLE $_tableName(&quot;
            &quot;id INTEGER PRIMARY KEY AUTOINCREMENT, &quot;
            &quot;title STRING, note TEXT, date STRING, &quot;
            &quot;startTime STRING, endTime STRING, &quot;
            &quot;remind INTEGER, repeat STRING, &quot;
            &quot;color INTEGER, &quot;
            &quot;isCompleted INTEGER)&quot;);
      });
    } catch (e) {
      print(e);
    }
  }

  static Future&lt;int&gt; insert(Task? task) async {
    print(&quot;Insert Function Called&quot;);
    return await _db?.insert(_tableName, task!.toJson()) ?? 1;
  }

  static Future&lt;List&lt;Map&lt;String, dynamic&gt;&gt;&gt; query() async {
    print(&quot;Query Function Called&quot;);
    return await _db!.query(_tableName); --&gt; **This is where I get the error**
  }
}

This is my task_controller.dart Code:

class TaskController extends GetxController {
  @override
  void onReady() {
    super.onReady();
  }

  var taskList = &lt;Task&gt;[].obs;

  Future&lt;int&gt; addTask({Task? task}) async {
    return await DBHelper.insert(task);
  }

  // get data from the table
  void getTasks() async {
    List&lt;Map&lt;String, dynamic&gt;&gt; tasks = await DBHelper.query();
    taskList.assignAll(tasks.map((data) =&gt; new Task.fromJson(data)).toList());
  }
}

This is a part of my home_page.dart file :

 _showTasks() {
    return Expanded(
      child: Obx(() {
        return ListView.builder(
            itemCount: _taskController.taskList.length,
            itemBuilder: (_, index) {
              return Container(
                width: 100,
                height: 50,
                color: Colors.green,
                margin: const EdgeInsets.only(bottom: 10),
                child: Text(
                  _taskController.taskList[index].title.toString(),
                ),
              );
            });
      }),
    );
  }

答案1

得分: 1

你正尝试使用空值检查操作符访问空值。错误发生的原因是在执行 _db!.query(_tableName)_db 为空。

确保在调用查询方法之前初始化 _db

static Future<List<Map<String, dynamic>>> query() async {
  print("Query Function Called");
  if (_db == null) {
    await initDb(); // 确保在查询之前初始化数据库
  }
  return await _db!.query(_tableName);
}
英文:

you are trying to access a null value using the null check operator. the error is occuring because _db is null when you try to execute _db!.query(_tableName)

make sure _db is initialized before calling the query method:

static Future&lt;List&lt;Map&lt;String, dynamic&gt;&gt;&gt; query() async {
  print(&quot;Query Function Called&quot;);
  if (_db == null) {
    await initDb(); // Ensure the database is initialized before querying
  }
  return await _db!.query(_tableName);
}

huangapple
  • 本文由 发表于 2023年7月7日 04:58:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76632492.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定