LateInitializationError: Field 'box' has not been initialized

39 Views Asked by At

I am creating an integration test for a Flutter project but I got an error The following LateError was thrown building Builder: LateInitializationError: Field 'box' has not been initialized. Basically, you can add bookmark on this app. (I removed some codes to make it simple). I have no idea how to solve this error. Please help me. Here is the codes.

main.dart

late Box box;
const bookmarkBox = 'bookmark_box';

Future<void> main() async {
  await Hive.initFlutter();
  box = await Hive.openBox(bookmarkBox);
  runApp(const BookmarkApp());
}
class _BookmarkListPageState extends State<BookmarkListPage> {

  // Google, Apple are default value
  List<dynamic> bookmarkList = box?.get('BookmarkTitle', defaultValue: ['Google', 'Apple']) ?? [];
  List<dynamic> bookmarkUrl = box?.get('BookmarkUrl', defaultValue: [
    'https://www.google.com/',
    'https://www.apple.com/jp/',
  ]) ?? [];
}
1

There are 1 best solutions below

1
Ivo On

Change

late Box box;

to

Box? box;

It doesn't need to be late and it's fine if it's nullable since you are checking for null anyway