Cash Trees
Cash Trees

Reputation: 1

Unhandled error LateInitializationError: Field 'currentUser' has not been initialized. occurred in Instance of 'HomeBloc'

so i do get this error : Unhandled Exception: Unhandled error LateInitializationError: Field 'currentUser' has not been initialized. occurred in Instance of 'HomeBloc'.

E/flutter (11536): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Unhandled error LateInitializationError: Field 'currentUser' has not been initialized. occurred in Instance of 'HomeBloc'. E/flutter (11536): #0 GlobalConstants.currentUser (package:fitness_flutter/core/const/global_constants.dart) E/flutter (11536): #1 DataService.getWorkoutsForUser (package:fitness_flutter/core/service/data_service.dart:9:43) E/flutter (11536): #2 HomeBloc.mapEventToState (package:fitness_flutter/screens/home/bloc/home_bloc.dart:27:36) E/flutter (11536):

Line 9 from data_service.dart : final currUserEmail = GlobalConstants.currentUser.mail;

Line 27 from home_bloc.dart : workouts = await DataService.getWorkoutsForUser();

This is my data_service.dart

import 'dart:convert';

import 'package:fitness_flutter/core/const/global_constants.dart';
import 'package:fitness_flutter/core/service/user_storage_service.dart';
import 'package:fitness_flutter/data/workout_data.dart';

class DataService {
  static Future<List<WorkoutData>> getWorkoutsForUser() async {
    final currUserEmail = GlobalConstants.currentUser.mail;

    // await UserStorageService.deleteSecureData('${currUserEmail}Workouts');

    final workoutsStr =
        await UserStorageService.readSecureData('${currUserEmail}Workouts');
    if (workoutsStr == null) return [];
    final decoded = (json.decode(workoutsStr) as List?) ?? [];
    final workouts = decoded.map((e) {
      final decodedE = json.decode(e) as Map<String, dynamic>?;
      return WorkoutData.fromJson(decodedE!);
    }).toList();
    GlobalConstants.workouts = workouts;
    return workouts;
  }

  static Future<void> saveWorkout(WorkoutData workout) async {
    final allWorkouts = await getWorkoutsForUser();
    final index = allWorkouts.indexWhere((w) => w.id == workout.id);
    if (index != -1) {
      allWorkouts[index] = workout;
    } else {
      allWorkouts.add(workout);
    }
    GlobalConstants.workouts = allWorkouts;
    final workoutsStr = allWorkouts.map((e) => e.toJsonString()).toList();
    final encoded = json.encode(workoutsStr);
    final currUserEmail = GlobalConstants.currentUser.mail;
    await UserStorageService.writeSecureData(
      '${currUserEmail}Workouts',
      encoded,
    );
  }
}

This is my global_constants.dart :

import 'package:fitness_flutter/data/user_data.dart';
import 'package:fitness_flutter/data/workout_data.dart';

class GlobalConstants {
  static late UserData currentUser;
  static late List<WorkoutData> workouts;
}

This is my home_bloc.dart

class HomeBloc extends Bloc<HomeEvent, HomeState> {
  HomeBloc() : super(HomeInitial());

  List<WorkoutData> workouts = <WorkoutData>[];
  List<ExerciseData> exercises = <ExerciseData>[];
  int timeSent = 0;

  @override
  Stream<HomeState> mapEventToState(
    HomeEvent event,
  ) async* {
    if (event is HomeInitialEvent) {
      workouts = await DataService.getWorkoutsForUser();
      yield WorkoutsGotState(workouts: workouts);
    } else if (event is ReloadImageEvent) {
      String? photoURL = await UserStorageService.readSecureData('image');
      if (photoURL == null) {
        photoURL = AuthService.auth.currentUser?.photoURL;
        photoURL != null
            ? await UserStorageService.writeSecureData('image', photoURL)
            : print('no image');
      }
      yield ReloadImageState(photoURL: photoURL);
    } else if (event is ReloadDisplayNameEvent) {
      final displayName = await UserStorageService.readSecureData('name');
      yield ReloadDisplayNameState(displayName: displayName);
    }
  }

Upvotes: 0

Views: 58

Answers (1)

bebe
bebe

Reputation: 114

This is because leading up to the line where you were trying to access currentUser, there was no where you set a value for it, unlike that for workouts. You can fix this by particular error by treating is as nullable if you expect it that way, or you initialize it with some value in that line or some other way.

Upvotes: 1

Related Questions