hive icon indicating copy to clipboard operation
hive copied to clipboard

_CastError Thrown Building Widget

Open jeremyw24 opened this issue 5 years ago • 0 comments

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:

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)

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:

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

jeremyw24 avatar Mar 04 '21 12:03 jeremyw24