isar / isar/hive

_CastError Thrown Building Widget

Open
#586 0 comments 0 reactions 0 assignees View on GitHub
question
Dominant language
Dart
Stars
4.4k
Forks
449
PR merge metrics
No merged PRs in 30d

Description

**Question**
New to hivedb and have become stuck on this issue I cant seem to move past...

Basically I have a box which has two fields, one stores a string and the other stores an int:

```dart
import 'package:hive/hive.dart';

part 'logs_history.g.dart';

@HiveType(typeId: 1)
class LogsHistory {
@HiveField(0)
final int logID;
@HiveField(1)
final String vessel;

LogsHistory(this.vessel, this.logID);
}
```

I then want to return the contents of the box as a list using WatchBoxBuilder (this works fine if the LogsHistory box is not created and/or empty)

```dart
Widget _buildListView() {
return WatchBoxBuilder(
box: Hive.box('logsHistory'),
builder: (context, logsBox) {
return ListView.builder(
itemCount: logsBox.length,
itemBuilder: (context, index) {
final logs = logsBox.getAt(index) as LogsHistory;

return ListTile(
title: Text(logs.logID.toString()),
subtitle: Text(logs.vessel),
);
},
);
},
);
}
```

Once a record is added to the box, in this case simply epoch in the logID Field:
```dart
final logsBox = Hive.box('logsHistory');
var newBox = DateTime.now().millisecondsSinceEpoch;
var createBox = await Hive.openBox('$newBox');
logsBox.put('logID', '$newBox');
```

The app will crash trying to display the list with error: `type 'String' is not a subtype of type 'LogsHistory' in type cast`

Using debug, I have been able to trace the error specifically to this line of the WatchBoxBuilder: `final logs = logsBox.getAt(index) as LogsHistory;`

But cant seem to figure out how to resolve it??

**Version**
- Platform: Android
- Flutter version: Flutter 1.22.6 / Dart 2.10.5
- Hive version: ^1.4.4+1

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.