skip to Main Content

======== Exception caught by widgets library ======================================================= The following LateError was thrown building KeyedSubtree-[GlobalKey#74540]:
LateInitializationError: Field ‘_persondb’ has not been initialized.

The relevant error-causing widget was: Scaffold
Scaffold:file:///C:/Users/Prive/StudioProjects/tanja/lib/person/screens/personsScreen/personsSreen.dart:18:16
When the exception was thrown, this was the stack:
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/internal/js_dev_runtime/private/ddc_runtime/errors.dart
266:49 throw

packages/tanja/person/personService/personService.dart 6:22
get [_persondb] packages/tanja/person/personService/personService.dart
15:31
getPersons
mount

……………………

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:tanja/person/personService/personService.dart';
import 'package:tanja/route.dart';

void main() async {
  await Hive.initFlutter();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MultiRepositoryProvider(
      providers: [
        RepositoryProvider(create: (context) => PersonService().getPersons()),
      ],
      child:   MaterialApp.router(
        routerConfig: goRouter,
        debugShowCheckedModeBanner: false,
        title: 'Flutter Demo',
      ),
    );
  }
}

service

import '../personmodel/personDB.dart';

class PersonService {
  late Box<PersonDB> _persondb;

  Future<void> init() async {
    if (!Hive.isAdapterRegistered(0)) {
      Hive.registerAdapter(PersonDBAdapter());
    }
    _persondb = await Hive.openBox<PersonDB>('persondb');
  }
  List<PersonDB> getPersons() {
    final persons = _persondb.values;
    return persons.toList();
  }

  void addPerson(final PersonDB personDB ) {
    _persondb.add(personDB);
  }
}

bloc

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:tanja/person/personService/personService.dart';

import '../../../personmodel/personDB.dart';


part 'persons_state.dart';

class PersonsCubit extends Cubit<PersonsState> {
  PersonService _personService;
  PersonsCubit(this._personService) : super(PersonsInitial());

  void loadPersonsData(){
    _personService.init();
    emit(PersonsDataLoaded(_personService.getPersons()));
  }
}

screen

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:tanja/person/screens/personsScreen/bloc/persons_cubit.dart';

import '../../personService/personService.dart';


class PersonsScreen extends StatelessWidget {
  const PersonsScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    PersonService  _personService= PersonService();
    return BlocProvider(
        create: (context){
          return PersonsCubit(_personService)..loadPersonsData();
        },
        child: Scaffold(
          appBar: AppBar(),
          body: BlocBuilder<PersonsCubit,PersonsState>(
              builder:(context, state) {
            if(state is PersonsInitial){
              return Text('$state');
            }else{
              return Text('$state');
            }
          }),
        )
    );
  }
}

2

Answers


  1. Try this

    //replace 
    //late Box<PersonDB> _persondb;
    //to this
    var _persondb;
    
    }
    
    Login or Signup to reply.
  2. The issue is from the loadPersonsData() function in the PersonsCubit class, _personService.init(); return a Future therefore the emit(PersonsDataLoaded(_personService.getPersons())); must wait for it to init completely to call _personService.getPersons().
    You could try to fix the loadPersonsData function as following:

    Future<void> loadPersonsData() async {
        await _personService.init();
        emit(PersonsDataLoaded(_personService.getPersons()));
      }
    

    Hope this helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search