简体   繁体   English

如何在 flutter 中的 sqflite 数据库中读写

[英]How to read and write in sqflite database in flutter

Good day everyone,今天是个好日子,

I am developing an App usaing Flutter.我正在使用 Flutter 开发一个应用程序。 To save some data localy I am using the SQFlite plugin.为了在本地保存一些数据,我使用了 SQFlite 插件。

I have a database helper class.我有一个数据库助手 class。 I am using Provider to call my database methods.我正在使用 Provider 来调用我的数据库方法。

When I call the method to write an account in the database I receive an autoincremented ID as response the the sucess of the insertion of the account.当我调用该方法在数据库中写入帐户时,我收到一个自动递增的 ID 作为帐户插入成功的响应。

The problem is when I call the method to read these accounts from the database I receiceive nothing.问题是当我调用该方法从数据库中读取这些帐户时,我什么也没收到。 The response Map is null like I have nothing in the database.响应 Map 是 null 就像我在数据库中没有任何内容一样。

If when I insert an account to my database I receive an ID as response, why when I try to read these account I receive nothing.如果当我在我的数据库中插入一个帐户时收到一个 ID 作为响应,为什么当我尝试读取这些帐户时我什么也没有收到。

Please help, me.请帮我。 I am going insane with this code.这段代码我快疯了。

class DBProvider {
  static const String TABLE_ACCOUNTS = 'Accounts';
  static const String COLUMN_ID = 'accountID';
  static const String COLUMN_LOCAL_ID = 'id';
  static const String COLUMN_CUSTOMER_PICTURE = 'customerPictureBase64';
  static const String COLUMN_DOC_FRONT = 'docFrontPictureBase64';
  static const String COLUMN_DOC_BACK = 'docBackPictureBase64';
  static const String COLUMN_SIGNATURE = 'signatureBase64';
  static const String COLUMN_GENDER = 'gender';
  static const String COLUMN_FIRST_NAME = 'firstName';
  static const String COLUMN_LAST_NAME = 'lastName';
  static const String COLUMN_DOC_TYPE = 'docType';

  DBProvider._();
  static final DBProvider db = DBProvider._();
  Database _database;

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

  Future<Database> createDatabase() async {
    String dbPath = await getDatabasesPath();
    return await openDatabase(
      join(dbPath, 'paperless.db'),
      version: 1,
      onCreate: (Database database, int version) async {
        await database.execute(
          'CREATE TABLE $TABLE_ACCOUNTS ($COLUMN_LOCAL_ID INTEGER PRIMARY KEY, $COLUMN_ID TEXT, '
          '$COLUMN_CUSTOMER_PICTURE TEXT, $COLUMN_DOC_FRONT TEXT, '
          '$COLUMN_DOC_BACK TEXT, $COLUMN_SIGNATURE TEXT, '
          '$COLUMN_GENDER INTEGER, $COLUMN_FIRST_NAME TEXT, '
          '$COLUMN_LAST_NAME TEXT, $COLUMN_DOC_TYPE TEXT)',
        );
      },
    );
  }

  Future<List<LowKYCAccount>> getLocalLowKYCAccount() async {
    final db = await database;

    var accounts = await db.rawQuery('SELECT * FROM $TABLE_ACCOUNTS');

    var accountsList = List<LowKYCAccount>();

    accounts.forEach((account) {
      LowKYCAccount kycAccount = LowKYCAccount.fromMap(account);
      accountsList.add(kycAccount);
    });
    return accountsList;
  }

  Future<LowKYCAccount> saveAccountLocaly(LowKYCAccount account) async {
    final db = await database;
    account.localId = await db.insert(TABLE_ACCOUNTS, account.toMap());
    return account;
  }
}

I am calling this methods from my UI sing provider我从我的 UI 唱歌提供者那里调用这些方法

class LowKYCProvider with ChangeNotifier {
  LowKYCAccount _selectedAccount;
  List<LowKYCAccount> _lowKycAccounts = [];
  List<LowKYCAccount> _localLowKycAccounts = [];

  LowKYCAccount get selectedAccount {
    return _selectedAccount;
  }

  List<LowKYCAccount> get lowKycAccounts {
    return [..._lowKycAccounts];
  }

  List<LowKYCAccount> get localLowKycAccounts {
    return [..._localLowKycAccounts];
  }

  Future<void> submitNewAccount(LowKYCAccount account) async {}

  Future<void> fetchLowKycAccounts() async {
    if (_lowKycAccounts.isEmpty) {
      notifyListeners();
    }
  }

  Future<void> fetchLocalLowKycAccounts() async {
    print('vamos fetchar os locais');
    await DBProvider.db.getLocalLowKYCAccount().then((accounts) {
      _localLowKycAccounts = accounts;
      //notifyListeners();
    });
    print('Já terminamos');
  }

  Future<void> saveAccountLocaly(LowKYCAccount account) async {
    await DBProvider.db
        .saveAccountLocaly(account)
        .then((account) => _localLowKycAccounts.add(account));
    notifyListeners();
  }

  Future<void> updateLowKycAccount(LowKYCAccount account) async {}

  Future<void> setSelectedAccount(int index) async {
    _selectedAccount = _lowKycAccounts[index];
    notifyListeners();
  }
}

this is the model class这是 model class

class LowKYCAccount {
  String id;
  int localId;
  String customerPictureBase64;
  String docFrontPictureBase64;
  String docBackPictureBase64;
  int gender;
  String firstName;
  String lastName;
  String docType;

  File signatureFile;
  String signatureUrl;

  LowKYCAccount({
    this.id,
    this.localId,
    this.customerPictureBase64,
    this.docFrontPictureBase64,
    this.docBackPictureBase64,
    this.gender,
    this.firstName,
    this.lastName,
    this.docType,
    this.signatureUrl,
    this.signatureFile,
  });

  Map<String, dynamic> toMap() {
    var map = <String, dynamic>{
      DBProvider.COLUMN_ID: id,
      DBProvider.COLUMN_CUSTOMER_PICTURE: customerPictureBase64,
      DBProvider.COLUMN_DOC_FRONT: docFrontPictureBase64,
      DBProvider.COLUMN_DOC_BACK: docBackPictureBase64,
      DBProvider.COLUMN_GENDER: gender,
      DBProvider.COLUMN_FIRST_NAME: firstName,
      DBProvider.COLUMN_LAST_NAME: lastName,
      DBProvider.COLUMN_DOC_TYPE: docType,
    };

    if (localId != null) {
      map[DBProvider.COLUMN_LOCAL_ID] = localId;
    }
    return map;
  }

  LowKYCAccount.fromMap(Map<String, dynamic> account) {
    id = account[DBProvider.COLUMN_ID];
    localId = account[DBProvider.COLUMN_LOCAL_ID];
    customerPictureBase64 = account[DBProvider.COLUMN_CUSTOMER_PICTURE];
    docFrontPictureBase64 = account[DBProvider.COLUMN_DOC_FRONT];
    docBackPictureBase64 = account[DBProvider.COLUMN_DOC_BACK];
    gender = account[DBProvider.COLUMN_GENDER];
    firstName = account[DBProvider.COLUMN_FIRST_NAME];
    lastName = account[DBProvider.COLUMN_LAST_NAME];
    docType = account[DBProvider.COLUMN_DOC_TYPE];
  }
}

No experience with this type of plugin or this database, but you should probably use transactions: Otherwise your data will probably not be committed:没有使用此类插件或此数据库的经验,但您可能应该使用事务:否则您的数据可能不会被提交:

await database.transaction((txn) async {
  var batch = txn.batch();

  // ... insert your data here!

  // commit but the actual commit will happen when the transaction is committed
  // however the data is available in this transaction
  await batch.commit();

  //  ...
});

and the insert example:和插入示例:

// Insert some records in a transaction
await database.transaction((txn) async {
  int id1 = await txn.rawInsert(
      'INSERT INTO Test(name, value, num) VALUES("some name", 1234, 456.789)');
  print('inserted1: $id1');
  int id2 = await txn.rawInsert(
      'INSERT INTO Test(name, value, num) VALUES(?, ?, ?)',
      ['another name', 12345678, 3.1416]);
  print('inserted2: $id2');
});

See https://pub.dev/packages/sqflite for more info on transactions有关交易的更多信息,请参阅https://pub.dev/packages/sqflite

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM