В приложении Flutter я получаю предупреждение: база данных заблокирована на 0:00:10.000000.Android

Форум для тех, кто программирует под Android
Ответить
Anonymous
 В приложении Flutter я получаю предупреждение: база данных заблокирована на 0:00:10.000000.

Сообщение Anonymous »

После добавления данных в локальную базу данных sqflite. Я продолжаю получать это предупреждение: база данных заблокирована на 0:00:10.000000. Убедитесь, что вы всегда используете объект транзакции для операций с базой данных во время транзакции.
И приложение не работает гладко.
class DBHelper {
static Database? _db;
Future get db async {
if (_db != null) return _db;
_db = await initDatabase();
return _db;
}

Future initDatabase() async {
io.Directory documentDirectory = await getApplicationDocumentsDirectory();
String path = join(documentDirectory.path,"cart.db");
var db = await openDatabase(path, version: 1, onCreate: _onCreate);
return db;
}

Future _onCreate(Database db, int version) async {
await db.execute(
'CREATE TABLE cart (id INTEGER PRIMARY KEY,user_id INTEGER ,item_id
INTEGER,main_item_id INTEGER,name TEXT,price REAL, qty INTEGER, type TEXT, image
TEXT, created_at TEXT, updated_at TEXT )');
}

// Insert a cart item
Future insert(getMyCart cart) async {
var dbClient = await db;
await dbClient!.insert('cart', cart.toJson());
return cart;
}

// Retrieve the list of cart items
Future getCartList() async {
var dbClient = await db;
final List queryResult =
await dbClient!.query('cart');
return queryResult.map((e) => getMyCart.fromJson(e)).toList();
}

// Delete a cart item by id
Future delete(int? id) async {
var dbClient = await db;
return await dbClient!.delete('cart', where: "id = ?", whereArgs: [id]);
}

// Delete all cart items
Future deleteAll() async {
var dbClient = await db;
await dbClient!.delete('cart');
}

// Update the quantity of a cart item
Future updateQuantity(getMyCart cart) async {
var dbClient = await db;
return await dbClient!
.update('cart', cart.toJson(), where: "id = ?", whereArgs: [cart.id]);
}

// Check if an item exists in the cart
Future itemExists(id) async {
var result = await _db!.rawQuery(
'SELECT EXISTS(SELECT * FROM cart WHERE item_id="$id")',
);
int? exists = Sqflite.firstIntValue(result);
return exists == 1;
}

Future itemExist(id) async {
dynamic result;
int? exists;
if (_db != null) {
result = await _db!.rawQuery(
'SELECT EXISTS(SELECT * FROM cart WHERE item_id="$id")',
);
exists = Sqflite.firstIntValue(result);
} else {
exists = 0;
}
return exists == 1;
}

При нажатии кнопки «Купить» я добавляю данные в локальную базу данных. Код нажатия кнопки Buyonce приведен ниже: -
GestureDetector(
onTap:
() async {
if (getcategoryList[selectedCategoryIndex]
.subCategory![
selectedSubcategoryIndex]
.item![
index]
.addonAdded ==
1) {
if (!itemCountMap.containsKey(getcategoryList[selectedCategoryIndex]
.subCategory![
selectedSubcategoryIndex]
.item![
index]
.id)) {
itemCountMap[getcategoryList[selectedCategoryIndex]
.subCategory![
selectedSubcategoryIndex]
.item![
index]
.id] = 1;
}
await showBottomSheet(
context,
getcategoryList[selectedCategoryIndex].subCategory![selectedSubcategoryIndex].item![
index],
itemCountMap[getcategoryList[selectedCategoryIndex].subCategory![selectedSubcategoryIndex].item![index].id] == 0
? 1
: itemCountMap[getcategoryList[selectedCategoryIndex].subCategory![selectedSubcategoryIndex].item![index].id],
false)
.then((onVal) async {
if (onVal !=
null) {
await cart
.getData()
.then((cartItemList) {
if (cartItemList
.isNotEmpty) {
setState(() {
myCartList = cartItemList;
itemCountMap[getcategoryList[selectedCategoryIndex].subCategory![selectedSubcategoryIndex].item![index].id] = onVal;
updateCount();
isbuynowclicked = selecteditemindex;
selecteditemindex = index;
});
}
});
}
});
if (itemCountMap[getcategoryList[selectedCategoryIndex]
.subCategory![selectedSubcategoryIndex]
.item![index]
.id] ==
0) {
itemCountMap[getcategoryList[selectedCategoryIndex]
.subCategory![
selectedSubcategoryIndex]
.item![
index]
.id] = 1;
}
buynowClicked[getcategoryList[selectedCategoryIndex]
.subCategory![
selectedSubcategoryIndex]
.item![
index]
.id] = true;
selecteditemindex =
index;
isbuynowclicked =
selecteditemindex;
} else {
bool isItemExist = await dbHelper.itemExists(getcategoryList[selectedCategoryIndex]
.subCategory![
selectedSubcategoryIndex]
.item![
index]
.id);
if (isiteminCart ==
false &&
isItemExist ==
false) {
await dbHelper
.insert(my_cart_model.getMyCart(
id: getcategoryList[selectedCategoryIndex].subCategory![selectedSubcategoryIndex].item![index].id,
userId: globalCurrentUserData.id,
itemId: getcategoryList[selectedCategoryIndex].subCategory![selectedSubcategoryIndex].item![index].id,
name: getcategoryList[selectedCategoryIndex].subCategory![selectedSubcategoryIndex].item![index].name,
price: getcategoryList[selectedCategoryIndex].subCategory![selectedSubcategoryIndex].item![index].offerPrice,
qty: 1,
type: getcategoryList[selectedCategoryIndex].subCategory![selectedSubcategoryIndex].item![index].type,
image: getcategoryList[selectedCategoryIndex].subCategory![selectedSubcategoryIndex].item![index].image,
createdAt: DateTime.now().toString(),
updatedAt: DateTime.now().toString()))
.then((result) async {
await cart
.getData()
.then((cartItemList) {
if (cartItemList
.isNotEmpty) {
for (int i = 0;
i < cartItemList.length;
i++) {
if (cartItemList.itemId == getcategoryList[selectedCategoryIndex].subCategory![selectedSubcategoryIndex].item![index].id) {
setState(() {
buynowClicked[getcategoryList[selectedCategoryIndex].subCategory![selectedSubcategoryIndex].item![index].id] = true;
selecteditemindex = index;
itemCountMap[getcategoryList[selectedCategoryIndex].subCategory![selectedSubcategoryIndex].item![index].id] = cartItemList.qty!;
isbuynowclicked = selecteditemindex;
myCartList = cartItemList;
updateCount();
});
}
}
}
});
});
}
}
},
child: (cartobj
.itemId ==
getcategoryList[selectedCategoryIndex]
.subCategory![selectedSubcategoryIndex]
.item![index]
.id)
? Padding(
padding: const EdgeInsets
.only(
right:
5),
child: counterContainer(
index,
getcategoryList[selectedCategoryIndex].subCategory![selectedSubcategoryIndex].item![index],
cartobj,
cart),
)
: Container(
width:
100.w,//100,//155,
height:
40.h,//37,
decoration:
BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(
10//6 //3
),
border:
Border.all(
width:
1,
color: const Color.fromRGBO(
49,
164,
113,
1),
),
),
child:
Center(
child:
Text(
buynowBtnText,
style:
GoogleFonts.metrophobic(
fontSize: 13,
fontWeight: FontWeight.w600,
color: const Color.fromRGBO(49, 164, 113, 1),
),
),
),
),
),


Подробнее здесь: https://stackoverflow.com/questions/790 ... 010-000000
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»