I had an error here in my cubit when I initialize the model.
import 'package:bloc/bloc.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:users_app/cubit/states.dart';
import '../dio_helper.dart';
import '../userModel.dart';
class UsersCubit extends Cubit<UsersStates> {
UsersCubit() : super(UsersInitialState());
static UsersCubit get(context) => BlocProvider.of(context);
late User userModel;
Future getUsers() async {
String url = '/users';
var response = await DioHelper.getData(url: url).then((value) {
emit(UsersLoadingState());
userModel = User.fromJson(value.data);
print(userModel.name);
emit(UsersGetDataSuccessState());
}).catchError((err) {
emit(UsersGetDataErrorState());
print(err);
});
}
}
and this is my model.
class User {
String? id;
String? name;
String? email;
String? imageUrl;
User.fromJson(Map<String, dynamic> json) {
id = json['_id'];
name = json['name'];
email = json['email'];
imageUrl = json['imageUrl'];
}
}
and this is the error.
LateInitializationError: Field 'userModel' has not been initialized.
I tried to change late User userModel to User ? userModel but I still getting the same issue please, anyone, know the answer of my error.
CodePudding user response:
If your method finishes in "catch" the userModel is never initialized, so you could do something like this:
Instead of:
late User userModel;
use:
User userModel = User();
CodePudding user response:
Your Cubit implementation is not actually following the pattern. BLoCs (and Cubits) should not have any public data. That is the whole point, that you have state management. Your BLoC (or Cubit) has a current state and that is what you can access.
Your UserModel variable belongs into a state. Something like "UsersGetDataSuccessState". Then your userModel can be a local variable:
final userModel = User.fromJson(value.data);
print(userModel.name);
emit(UsersGetDataSuccessState(userModel));
Because this only exists when the user was loaded successfully, so it should be a property of that state, not of the BLoC.