drift
drift copied to clipboard
Error while trying to insert a record
LOG
E/flutter (21585): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: LateInitializationError: Field '_db@1324164674' has not been initialized.
E/flutter (21585): #0 Sqlite3Delegate._db (package:drift/src/sqlite3/database.dart)
package:drift/…/sqlite3/database.dart:1
E/flutter (21585): #1 Sqlite3Delegate._runWithArgs
package:drift/…/sqlite3/database.dart:110
E/flutter (21585): #2 Sqlite3Delegate.runInsert
package:drift/…/sqlite3/database.dart:127
E/flutter (21585): #3 _BaseExecutor.runInsert.<anonymous closure>
package:drift/…/helpers/engines.dart:99
E/flutter (21585): #4 _BaseExecutor._synchronized.<anonymous closure>
package:drift/…/helpers/engines.dart:51
E/flutter (21585): #5 new Future.sync (dart:async/future.dart:301:31)
E/flutter (21585): #6 Lock.synchronized.callBlockAndComplete
package:drift/…/utils/synchronized.dart:17
E/flutter (21585): #7 Lock.synchronized.<anonymous closure>
package:drift/…/utils/synchronized.dart:21
E/flutter (21585): #8 _rootRunUnary (dart:async/zone.dart:1434:47)
E/flutter (21585): #9 _CustomZone.runUnary (dart:async/zone.dart:1335:19)
E/flutter (21585): <asynchronous suspension>
E/flutter (21585): #10 InsertStatement.insert.<anonymous closure>
package:drift/…/statements/insert.dart:74
E/flutter (21585): <asynchronous suspension>
E/flutter (21585): #11 InsertStatement.insert
package:drift/…/statements/insert.dart:73
E/flutter (21585): <asynchronous suspension>
E/flutter (21585): #12 DealCardState._buildDealCardAddFavoriteButton.<anonymous closure>.<anonymous closure>
package:deal_hunter/…/widgets/deal_card.dart:530
E/flutter (21585): <asynchronous suspension>
E/flutter (21585):
MY CODE
import 'dart:io';
import 'package:drift/drift.dart';
import 'package:drift/native.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
part 'deals_favorites.g.dart';
class Favorites extends Table {
TextColumn get title => text().nullable()();
TextColumn get dealId => text().customConstraint('UNIQUE')();
IntColumn get storeId => integer().nullable()();
RealColumn get salePrice => real().nullable()();
RealColumn get dealRating => real().nullable()();
RealColumn get normalPrice => real().nullable()();
RealColumn get savings => real().nullable()();
BlobColumn get dealImage => blob().nullable()();
BlobColumn get storeIconImage => blob().nullable()();
IntColumn get steamRatingPercent => integer().nullable()();
IntColumn get lastChange => integer().nullable()();
IntColumn get releaseDate => integer().nullable()();
IntColumn get metacriticScore => integer().nullable()();
}
@DriftDatabase(tables: [Favorites])
class AppDatabase extends _$AppDatabase {
AppDatabase() : super(_openConnection());
@override
int get schemaVersion => 1;
Stream<List<Favorite>> getAllFavorites() => select(favorites).watch();
Future<void> addToFavorites(Favorite favorite) =>
into(favorites).insert(favorite);
Future<void> removeFromFavorites(String dealsId) =>
(delete(favorites)..where((fav) => fav.dealId.equals(dealsId))).go();
Stream<bool> isFavorite(String dealId) {
return select(favorites).watch().map((favoritesList) =>
favoritesList.any((favorite) => favorite.dealId == dealId));
}
}
LazyDatabase _openConnection() {
return LazyDatabase(
() async {
final dbFolder = await getApplicationDocumentsDirectory();
final file = File(
path.join(
dbFolder.path,
'db.sqlite',
),
);
return NativeDatabase(file, logStatements: true);
},
);
}
Thanks for the report. Nothing stands out from the code (it looks very similar to some examples in this repository that work). Could you check which drift version you're using? Also, do you know what the first query is? Is anything being logged before that? What are you doing in DealCardState._buildDealCardAddFavoriteButton.<anonymous closure>.<anonymous closure>?
I'm using the latest version of drift 1.7.0
Any information on the method you're calling first? Can I copy your code and just call any method to reproduce it?
And just out of interest, does the error go away if you delete your app's data? Perhaps the database is broken (but in that case drift should still report a much better error).
I have a button to favorite or unfavorite an item.
StreamBuilder<bool> _buildDealCardAddFavoriteButton(AppDatabase appDatabase) {
return StreamBuilder<bool>(
stream: appDatabase.isFavorite(widget.dealId!),
builder: (context, snapshot) {
if (snapshot.hasData && snapshot.data!) {
return SizedBox(
height: 40,
child: OutlinedButton(
style: Theme.of(context).outlinedButtonTheme.style!.copyWith(
side: MaterialStateProperty.all(
const BorderSide(
color: AppDarkThemeColors.favoriteColor,
),
),
),
onPressed: () async {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('Confirm'),
content: const Text(
'Are you sure you want to unfavorite this deal?',
),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('Cancel'),
),
OutlinedButton(
onPressed: () async {
await appDatabase
.removeFromFavorites(widget.dealId!);
Navigator.of(context).pop();
setState(() {
isExpanded = false;
});
},
style: Theme.of(context).outlinedButtonTheme.style,
child: const Text('Unfavorite'),
),
],
titleTextStyle: Theme.of(context).textTheme.headline6,
),
);
},
child: const Center(
child: Icon(
DealHunterIcons.star,
color: AppDarkThemeColors.favoriteColor,
size: 18,
),
),
),
// ),
);
} else {
return SizedBox(
height: 40,
child: OutlinedButton(
onPressed: () async {
// Load interstitial ad when every user save the deal as favorite
// await loadInterstitialAd();
final image = widget.thumb!;
final storeIcon = '$iconsUrl${widget.storeId! - 1}.png';
final dealImage = await convertToUnit8ListImage(url: image);
final storeIconImage =
await convertToUnit8ListImage(url: storeIcon);
await appDatabase.addToFavorites(
Favorite(
title: widget.title,
steamRatingPercent: widget.steamRatingPercent,
dealId: widget.dealId!,
storeId: widget.storeId!,
salePrice: widget.salePrice!,
dealRating: widget.dealRating!,
normalPrice: widget.normalPrice!,
savings: widget.savings!,
dealImage: dealImage,
lastChange: widget.lastChange!,
releaseDate: widget.releaseDate!,
storeIconImage: storeIconImage,
metacriticScore: widget.metacriticScore,
),
);
},
style: Theme.of(context).outlinedButtonTheme.style,
child: const Icon(
DealHunterIcons.star,
size: iconSize,
),
),
);
}
});
}
The button will end up in a row of buttons
...
child: Row(
children: [
_buildDealCardGoToDealButton(dealIdUrl),
const SizedBox(
width: 8,
),
_buildDealCardShareButton(dealIdUrl),
const SizedBox(
width: 8,
),
_buildDealCardAddFavoriteButton(appDatabase),
],
),
...
The app was working until i upgraded from flutter 2 => flutter 3, and I have no idea with i going on!
The app was working until i upgraded from flutter 2 => flutter 3, and I have no idea with i going on!
Just to rule it out, have you tried re-running build_runner?
flutter pub run build_runner clean
flutter pub run build_runner build --delete-conflicting-outputs