首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >插入SQFlite数据库时抛出异常的Dart SQFlite()

插入SQFlite数据库时抛出异常的Dart SQFlite()
EN

Stack Overflow用户
提问于 2022-05-28 23:19:52
回答 1查看 90关注 0票数 -1

我很难将DateTime.toIso8601String()插入到Dart中的SQLite (SQFlite)数据库中。我遇到的问题是一个property_model类,它唯一的工作就是与数据库交互并保存数据。我有一个几乎相同的address_model类,它的工作方式与我所期望的一样,但我在property_model上遇到了麻烦。每当我试图调用Property.insert()方法时,都会得到以下错误:

错误:

/lib/ui/ui_dart_state.cc(209)未处理的异常:无效参数:'DateTime‘实例

不过,我和非常相似的地址类没有这个问题,而且我很困惑。下面是我使用的property_model、address_model和数据库文件( database.dart文件是我在整个应用程序中使用的单例文件)。

property_model.dart

代码语言:javascript
复制
import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';

import 'package:villadex/model/database.dart' as db;
import 'package:villadex/model/address_model.dart';

class Property {
  /// Constructors
  Property({
    required this.name,
    required Address address,
    required this.owner,
  })  : _address = address,
        _primaryKey = null,
        _dateCreated = DateTime.now();

  Property.existing(
      {required this.name,
      required Address address,
      required this.owner,
      required int? primaryKey,
      required DateTime dateCreated})
      : _address = address,
        _primaryKey = primaryKey,
        _dateCreated = dateCreated;

  Property.fromJSON({required Map<String, dynamic> json})
      : name = json['name'],
        owner = json['owner'],
        _address = Address.fromJson(json: json['location']),
        _primaryKey = json['property_id'],
        _dateCreated = DateTime.fromMillisecondsSinceEpoch(json['dateCreated']);

  /// Data
  String name;
  String? owner;
  final Address _address;

  /*final List<Event> calendar;
  final List<Expenditure> expenditures;
  final List<Associate> associates;
  final List<Earning> earnings;*/

  final int? _primaryKey;
  final DateTime _dateCreated;

  ///Methods
  Future<void> insert() async {
    String dateCreated = _dateCreated.toIso8601String().trim();

    Map<String, dynamic> data = {
      // SQFlite sets the primary key
      'name': name,
      'owner': owner,
      'location': address.toJson(),
      'dateCreated': dateCreated,
    };

    await db.DatabaseConnection.database.then((databaseConnection) => {
          databaseConnection?.insert('properties', data,
              conflictAlgorithm: ConflictAlgorithm.replace)
        });
  }

  static Future<Property?> fetchById(int id) async {
    String sql = "SELECT * FROM properties WHERE property_id = $id";

    Future<List<Map<String, dynamic>>>? rawData;
    await db.DatabaseConnection.database.then(
        (databaseConnection) => {rawData = databaseConnection?.rawQuery(sql)});

    return rawData?.then((data) {
      return Property.fromJSON(json: data[0]);
    });
  }

  /// Getters
  Address get address => _address;
}

address_model.dart

代码语言:javascript
复制
import 'package:flutter/material.dart';

import 'package:villadex/model/database.dart' as db;

class Address {
  /// Constructors
  Address(
      {required this.street1,
      this.street2 = '',
      required this.city,
      this.state = '',
      this.zip = '',
      required this.country})
      : _dateCreated = DateTime.now(),
        _primaryKey = null,
        _propertyId = null,
        _associateId = null;

  Address.existing({
    required this.street1,
    this.street2 = '',
    required this.city,
    this.state = '',
    this.zip = '',
    required this.country,
    required DateTime dateCreated,
    required int primaryKey,
    int? propertyKey,
    int? associateKey,
  })  : _dateCreated = dateCreated,
        _primaryKey = primaryKey,
        _propertyId = propertyKey,
        _associateId = associateKey;

  Address.fromJson({required Map<String, dynamic> json})
      : street1 = json['street1'],
        street2 = json['street2'],
        city = json['city'],
        state = json['state'],
        zip = json['zip'],
        country = json['country'],
        _primaryKey = json['address_id'],
        _propertyId = json['property_id'],
        _associateId = json['associate_id'],
        _dateCreated = DateTime.parse(json['_dateCreated']);

  /// Data
  final String street1;
  final String street2;
  final String city;
  final String state;
  final String zip;
  final String country;

  final int? _primaryKey;
  final int? _propertyId;
  final int? _associateId;
  final DateTime _dateCreated;

  /// Methods
  Future<void> insert() async {
    Map<String, dynamic> data = {
      // SQFlite sets the primaryKey
      'property_id': _propertyId,
      'associate_id': _associateId,
      'dateCreated': _dateCreated.toIso8601String().trim(),
      'street1': street1,
      'street2': street2,
      'city': city,
      'zip': zip,
      'country': country
    };

    await db.DatabaseConnection.database.then((databaseConnection) =>
        {databaseConnection?.insert('addresses', data)});
  }

  // Returns an address by ID
  static Future<Address?> fetchById(int id) async {
    String sql = "SELECT * FROM addresses WHERE address_id = $id";

    Future<List<Map<String, dynamic>>>? rawData;
    await db.DatabaseConnection.database.then(
        (databaseConnection) => {rawData = databaseConnection?.rawQuery(sql)});

    return rawData?.then((data) {
      return Address.fromJson(json: data[0]);
    });
  }

  Map<String, dynamic> toJson() {
    return {
      'street1': street1,
      'street2': street2,
      'city': city,
      'state': state,
      'zip': zip,
      'country': country,
      'address_id': _primaryKey,
      'property_id': _propertyId,
      'associate_id': _associateId,
      'dateCreated': _dateCreated
    };
  }

  /// Getters
  String get fullAddress =>
      street1 +
      " " +
      street2 +
      ", " +
      city +
      " " +
      state +
      " " +
      zip +
      ", " +
      country;

  DateTime get dateCreated => _dateCreated;

  int get key => _primaryKey ?? 0;

  /// Setters
}

database.dart

代码语言:javascript
复制
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:async';

import 'package:villadex/model/property_model.dart';


class DatabaseConnection {
  //static final DatabaseConnection instance = DatabaseConnection.init();

  //DatabaseConnection._init();

  /// Database variable
  static Database? _database;

  /// Getter for the database
  static Future<Database?> get database async {
    // If _database is null, set it equal to the return value of _initDB
    _database ??= await _initDB('database3');

    return _database;
  }

  /// Initialize database
  static Future<Database?> _initDB(String dbname) async {
    final dbPath = await getApplicationDocumentsDirectory();
    final path = join(dbPath.toString(), dbname);

    var dbInstance = await openDatabase(path, version: 1, onCreate: _createDatabase);

    return dbInstance;
  }

  /// Create the database
  static Future _createDatabase(Database database, int version) async {
    Batch batch = database.batch();

    /// CREATE PROPERTIES TABLE
    batch.execute('''CREATE TABLE properties(
      property_id INTEGER PRIMARY KEY,
      dateCreated TEXT NOT NULL,

      name TEXT NOT NULL,
      location TEXT NOT NULL,
      owner TEXT NOT NULL,
    
      calendar TEXT,
      expenditures TEXT,
      associates TEXT,
      earnings TEXT
      );''');

    /// CREATE EXPENDITURES TABLE
    batch.execute('''CREATE TABLE expenditures(
      expenditure_id INTEGER PRIMARY KEY,
      property_id INTEGER NOT NULL,
      dateCreated TEXT NOT NULL,

      name TEXT NOT NULL,
      amount REAL NOT NULL,
      numberUnits INTEGER NOT NULL,
      isPaid INTEGER NOT NULL,

      description TEXT,
      category TEXT,
      date TEXT,
      associates TEXT,

      FOREIGN KEY (property_id)
        REFERENCES properties(property_id)
      );''');

    /// CREATE EARNINGS TABLE
    batch.execute(''' CREATE TABLE earnings(
      earning_id INTEGER PRIMARY KEY,
      property_id INTEGER NOT NULL,
      dateCreated TEXT NOT NULL,

      name TEXT NOT NULL,
      amount REAL NOT NULL,

      description TEXT,
      category TEXT,
      date TEXT,
      associates TEXT,

      FOREIGN KEY (property_id)
        REFERENCES properties(property_id)
      );''');

    /// CREATE CATEGORIES TABLE
    batch.execute(''' CREATE TABLE categories(
      category_id INTEGER NOT NULL,
      dateCreated TEXT NOT NULL,

      name TEXT NOT NULL
      );''');

    /// CREATE ASSOCIATES TABLE
    batch.execute(''' CREATE TABLE associates(
      associate_id INTEGER PRIMARY KEY,
      property_id INTEGER NOT NULL,
      dateCreated TEXT NOT NULL,

      name TEXT NOT NULL,

      contact TEXT,
      role TEXT,
      payments TEXT,
      FOREIGN KEY (property_id)
        REFERENCES properties (property_id)
      );''');

    /// CREATE CONTACTS TABLE
    batch.execute(''' CREATE TABLE contact (
      associate_id INTEGER NOT NULL,

      phoneNumber TEXT,
      email TEXT,
      FOREIGN KEY (associate_id)
        REFERENCES associates (associate_id)
      );''');

    /// CREATE ADDRESSES TABLE
    batch.execute(''' CREATE TABLE addresses (
      address_id INTEGER PRIMARY KEY,
      property_id INTEGER,
      associate_id INTEGER,
      dateCreated TEXT NOT NULL,

      street1 TEXT NOT NULL,
      street2 TEXT,
      city TEXT NOT NULL,
      zip TEXT,
      state TEXT,
      country TEXT,
      FOREIGN KEY (property_id)
        REFERENCES properties (property_id),
      FOREIGN KEY (associate_id)
        REFERENCES associates (associate_id)
      );''');

    /// CREATE EVENT TABLE
    batch.execute(''' CREATE TABLE event (
      event_id INTEGER PRIMARY KEY,
      property_id INTEGER NOT NULL,
      dateCreated TEXT NOT NULL,

      name TEXT NOT NULL,

      description TEXT,
      address TEXT,
      associates TEXT,
      expenditures TEXT,
      earnings TEXT,

      FOREIGN KEY (property_id)
        REFERENCES properties (property_id)
      );''');

    batch.commit();
  }

  Future close() async {
    _database?.close;
  }
}

谢谢你的帮助!

EN

回答 1

Stack Overflow用户

发布于 2022-05-29 01:09:21

我想通了。在address.toJson()方法期间,me对象中的address对象没有将其address.toJson对象转换为字符串,这就是为什么它给出了该错误。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72419881

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档