perpetio/fitness

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

AdriansSB opened this issue · 1 comments

Hello, i was following the tutorial from your site and I do get this error :
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 'Home Bloc'. 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): <asynchronous suspension>

I did follow the tutorial exactly.

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,
    );
  }
}

home_bloc.dart :

import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:fitness_flutter/core/const/data_constants.dart';
import 'package:fitness_flutter/core/service/auth_service.dart';
import 'package:fitness_flutter/core/service/data_service.dart';
import 'package:fitness_flutter/core/service/user_storage_service.dart';
import 'package:fitness_flutter/data/exercise_data.dart';
import 'package:fitness_flutter/data/workout_data.dart';
import 'package:meta/meta.dart';

part 'home_event.dart';
part 'home_state.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);
    }
  }

  int getProgressPercentage() {
    final completed = workouts
        .where((w) =>
            (w.currentProgress ?? 0) > 0 && w.currentProgress == w.progress)
        .toList();
    final percent01 =
        completed.length.toDouble() / DataConstants.workouts.length.toDouble();
    final percent = (percent01 * 100).toInt();
    return percent;
  }

  int? getFinishedWorkouts() {
    final completedWorkouts =
        workouts.where((w) => w.currentProgress == w.progress).toList();
    return completedWorkouts.length;
  }

  int? getInProgressWorkouts() {
    final completedWorkouts = workouts.where(
        (w) => (w.currentProgress ?? 0) > 0 && w.currentProgress != w.progress);
    return completedWorkouts.length;
  }

  int? getTimeSent() {
    for (final WorkoutData workout in workouts) {
      exercises.addAll(workout.exerciseDataList!);
    }
    final exercise = exercises.where((e) => e.progress == 1).toList();
    exercise.forEach((e) {
      timeSent += e.minutes!;
    });
    return timeSent;
  }
}

Hello! Do you have any issues while following the tutorial? Because the application won't run on my device