尝试插入数据时,Sqflite给出堆栈错误

时间:2019-01-24 13:02:53

标签: dart flutter sqflite

我只是想将用户保存到我的数据库中。以下是我的用户模型类

class User {
  int _id;
  String _userId;
  String _mobileNumber;

  User([this._userId, this._mobileNumber]);

  User.withId(this._id, this._userId, this._mobileNumber);

  int get id => _id;

  String get userId => _userId;

  String get mobileNumber => _mobileNumber;

  set userId(String newUserId) {
    this.userId = newUserId;
  }

  set mobileNumber(String newMobileNumber) {
    this.mobileNumber = newMobileNumber;
  }

  Map<String, dynamic> toMap() {
    var map = Map<String, dynamic>();
    if (id != null) {
      map["id"] = _id;
    }
    map["userId"] = _userId;
    map["mobileNumber"] = _mobileNumber;

    return map;
  }

  User.fromMapObject(Map<String, dynamic> map) {
    this._id = map["id"];
    this._mobileNumber = map["userId"];
    this._userId = map["mobileNumber"];
  }
}

这是我的存储库类

class UserRepository {
  static UserRepository _userRepository;
  static Database _database;

  String userTable = "user";
  String colId = "id";
  String colUserId = "userId";
  String colMobileNumber = "mobileNumber";
  String databaseName = "dice.db";

  UserRepository._createInstance();

  factory UserRepository() {
    if (_userRepository == null) {
      _userRepository = UserRepository._createInstance();
    }
    return _userRepository;
  }

  Future<Database> get database async {
    if (_database == null) {
      _database = await initializeDatabase();
    }
    return _database;
  }

  Future<Database> initializeDatabase() async {
    Directory directory = await getApplicationDocumentsDirectory();
    String path = directory.path + databaseName;

    var userDatabase =
        await openDatabase(path, version: 1, onCreate: _createDb);
    return userDatabase;
  }

  void _createDb(Database db, int newversion) async {
    await db.execute(
        "CREATE TABLE $userTable($colId INTEGER PRIMARY KEY AUTOINCREMENT,$colUserId TEXT, $colMobileNumber TEXT)");
  }

  Future<List<Map<String, dynamic>>> getUserMapList() async {
    Database db = await this.database;
    return await db.query(userTable);
  }

  Future<int> insertUser(User user) async {
    Database db = await this.database;
    return await db.insert(userTable, user.toMap());
  }

  Future<int> updateNote(User user) async {
    var db = await this.database;
    return await db.update(userTable, user.toMap(),
        where: "$colId = ?", whereArgs: [user.id]);
  }

  Future<List<User>> getUserList() async {
    var userMapList = await getUserMapList();

    List<User> userList = List<User>();
    //We have only one user so i am only getting user at 0th position
    userList.add(User.fromMapObject(userMapList[0]));
    return userList;
  }
}

var userRepository = UserRepository();

现在在主类中单击按钮时,我正在编写以下代码以保存用户

  User user = User();
    user.mobileNumber = mobileData.data.mobile.toString();
    user.userId = mobileData.data.userid.toString();
    userRepository.insertUser(user).then((result) {
      if (result != 0) {
        print("Successfully saved to database");
      } else {
        print("Error saving to database");
      }
    });

以下是我单击按钮时的错误

[ERROR:flutter/shell/common/shell.cc(184)] Dart Error: Unhandled exception:
E/flutter (23914): Stack Overflow
E/flutter (23914): #0      User.mobileNumber= (package:dice_clutter/repository/User.dart:20:3)
E/flutter (23914): #1      User.mobileNumber= (package:dice_clutter/repository/User.dart:21:10)

RootZone.runUnary (dart:async/zone.dart:1379:54)
E/flutter (23914): #19311  _FutureListener.handleValue (dart:async/future_impl.dart:129:18)
E/flutter (23914): #19312  Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:642:45)
E/flutter (23914): #19313  Future._propagateToListeners (dart:async/future_impl.dart:671:32)
E/flutter (23914): #19314  Future._complete (dart:async/future_impl.dart:476:7)
E/flutter (23914): #19315  _SyncCompleter.complete (dart:async/future_impl.dart:51:12)
E/flutter (23914): #19316  _AsyncAwaitCompleter.complete (dart:async/runtime/libasync_patch.dart:28:18)
E/flutter (23914): #19317  _completeOnAsyncReturn (dart:async/runtime/libasync_patch.d          

我仅创建我的存储库类的一个引用。 任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

您使用了设置器的名称,因此出现了堆栈溢出

更改此:

set userId(String newUserId) {
  this.userId = newUserId;
}

set mobileNumber(String newMobileNumber) {
  this.mobileNumber = newMobileNumber;
}

对此:

  set userId(String newUserId) {
     _userId = newUserId;
  }

  set mobileNumber(String newMobileNumber) {
    _mobileNumber = newMobileNumber;
   }

答案 1 :(得分:1)

问题似乎是由此设置程序引起的:

  set mobileNumber(String newMobileNumber) {
    this.mobileNumber = newMobileNumber;
  }

设置this.mobileNumber将导致运行setter,因此在setter方法内调用将导致无限循环和堆栈溢出异常。

要解决此问题,请设置私有变量:

  set mobileNumber(String newMobileNumber) {
    _mobileNumber = newMobileNumber;
  }

您应该在userId设置程序上执行相同的操作,因为这会遇到相同的问题。