I am writing a little code in flutter where I am using Hive. this is the code
    import 'package:flutter/material.dart';
    
    import 'package:path_provider/path_provider.dart';
    
    import 'package:hive_flutter/hive_flutter.dart';
    import 'posts.dart';
    
    
    late Box box;
    
    Future<void> main() async {
      WidgetsFlutterBinding.ensureInitialized();
      final appDocumentDirectory = await getApplicationDocumentsDirectory();
      Hive.init(appDocumentDirectory.path);
      Hive.initFlutter();
      Hive.registerAdapter(PostsAdapter());
      print('adapter registered');
      box = await Hive.openBox<Posts>('posts');
      print('this is the box content ${box.values}');
      box.put('identifier:', Posts(identifier: '1', name: 'somename'));
      print(box.values);
      print(box.isEmpty);
      print('new values were added to the post');
      runApp(ExampleApp());
      }
    class ExampleApp extends StatelessWidget {
      const ExampleApp({Key? key}) : super(key: key);
    
      @override
    
      Widget build(BuildContext context) {
        Posts psts = box.get('posts');
    
        return MaterialApp(
            home: Scaffold(
              appBar: AppBar(
              title: Text("${psts.identifier}${psts.name}"),
            ),
        body: const Text('something to test'),
        ),);
      }
    }
the prints show what I would expect for results. the Box has an instance of Posts and with print(box.isEmpty) It is returning false.
the error that I receive is the following:
The following _TypeError was thrown building ExampleApp(dirty):
type 'Null' is not a subtype of type 'Posts'
also this is the class Posts to complete the picture.
import 'package:hive/hive.dart';
part 'posts.g.dart';
@HiveType(typeId: 0)
class Posts extends HiveObject{
  @HiveField(0)
  late String? identifier;
  @HiveField(1)
  late String? name;
  Posts({required this.identifier, required this.name});
}
what am I doing wrong?
edit: I think I have narrowed down area of issue to the first Line in the build method. somehow the Posts psts = box.get('posts'); has something wrong with it.
I had a similar problem when adding a new field to a TypeAdapter. I had it fixed by:
flutter cache clean & flutter pub getflutter packages pub run build_runner buildIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With