gpt4 book ai didi

android - SQLite 连接在 Flutter 中返回 null

转载 作者:IT王子 更新时间:2023-10-29 06:40:34 37 4
gpt4 key购买 nike

我在我的应用程序中使用 SQFLite flutter 包。但是,由于连接到数据库,我一直得到空值。下面是我在初始化数据库、创建表以及添加和获取项目的方法中使用的代码:

  import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';
import 'package:path/path.dart';
import 'dart:async';

class StoreDBProvider {

Database db;

init() async {
Directory documentsDirectory = await
getApplicationDocumentsDirectory();
final path = join(documentsDirectory.path, "carts.db");
db = await openDatabase(
path,
version: 3,
onCreate: (Database newDB, int version){
newDB.execute('CREATE TABLE Cart (id INTEGER
PRIMARY KEY, name TEXT, price DOUBLE, image TEXT, rating DOUBLE)');
}
);
return db;
}


Future<dynamic> fetchItem(int id) async {
print("DB CONNECTION IS: $db");

final maps = await db.query(
"Cart",
columns: null,
where: "id = ?",
whereArgs: [id],
);

print(maps);

if(maps.length > 0){
print("Data exists");
return maps.first;
}

return null;
}


Future<int> addItem(item) async{
return db.insert("Cart", item);
}
}

经过一些调试后,我注意到“db”值为空。这是错误消息:

 E/flutter ( 6921): [ERROR:flutter/shell/common/shell.cc(182)] Dart 
Error: Unhandled exception:
E/flutter ( 6921): NoSuchMethodError: The method 'insert' was called on null.
E/flutter ( 6921): Receiver: null
E/flutter ( 6921): Tried calling: insert("Cart", _LinkedHashMap len:5)
E/flutter ( 6921): #0 Object.noSuchMethod
(dart:core/runtime/libobject_patch.dart:50:5)
E/flutter ( 6921): #1 StoreDBProvider.addItem

(file:///Users/Oluwashola/workspace/fashion_style/lib/src/resources/store_db_provider.dart:46:15)

请在此提供任何帮助。谢谢。

最佳答案

如果有帮助,这是我的工作代码。请注意,当在方法中使用数据库时,我对数据库使用异步 getterawait 。恐怕我也是一个 Flutter 新手。

请注意,我通过 Future 与 DatabaseHelper 交互。请参见第二个代码块。我认为这需要使用 FutureBuilder .我怀疑您需要使用它来应对加载异步数据库调用(稍微)缓慢。

class DatabaseHelper {
final String tableName = "Gear";

static Database _db;

Future<Database> get db async {
if (_db != null) return _db;
_db = await initDb();
await importData();
return _db;
}

initDb() async {
// Get a location using path_provider
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, "gear_log.db");

await deleteDatabase(path);
var theDb = await openDatabase(path, version: 1,
onCreate: (Database db, int version) async {
print('creating db...');

String sql = await rootBundle.loadString('assets/db/schema.txt');
for (var s in sql.split(";")) {
if (s.length > 5) {
// catching any hidden characters at end of schema
await db.execute(s + ';');
}
}
// When creating the db, create the table
});

return theDb;
}

importData() async {
final datasources =
'observation_bodyissue.json,observation_observation.json,observation_observation_bodyIssues.json,observation_observation_shoeIssues.json,observation_shoeissue.json,observation_gearissue.json,runner_runner.json,gear_actualpair.json,gear_characteristic.json,gear_shoe.json,gear_family.json,gear_maker.json,gear_gear.json,gear_gear_characteristics.json,users_user.json'
.split(',');
var batch = _db.batch();

for (var datasource in datasources) {
try {
String str = await rootBundle.loadString('assets/db/data/$datasource');
String table = datasource.split('.')[0];

if (str.length > 0 && str != '[]') {
List<dynamic> _list = await json.decode(str);
for (var _json in _list) {
batch.insert(table, _json);
}
}
} catch (e) {
print(e.toString());
}
}
print('added db data');
var results = await batch.commit();
//print(results);
//print('imported data');
}

Future<List<Item>> getItems() async {
var dbClient = await db;

List<Map> list = await dbClient.rawQuery('SELECT *'
'FROM "gear_actualpair" '
'DESC, "gear_actualpair"."created" DESC');

//prob need to specify 'first X' at sometime

List<Item> items = new List();
for (int i = 0; i < list.length; i++) {
Item item = Item.fromMap(list[i]);
if (list[i]['selected'] == 1) {
item.observations = await getObservations(list[i]['id']);
}
items.add(item);
}

return items;
}
}

与 dbHelper 类交互:

Future<List<Item>> fetchItemsFromDatabase() async {
var dbHelper = DatabaseHelper();
Future<List<Item>> items = dbHelper.getItems();
return items;
}

关于android - SQLite 连接在 Flutter 中返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52741460/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com