'How can i solve Flutter The final variable cant be read error?
In my project i have a auth service but while trying use my service its giving a error like ;
" The final variable "_authService" can't be read coz it is potentially unassigned at this point. Ensure that it is assigned on necessary execution paths. "
I can show my service like :
abstract class IAuthService {
final String authPath =
'${IAuthServicePath.BASE_URL.rawValue}${IAuthServicePath.LOGIN}';
Future<AuthResponseModel?> login(AuthRequstModel model);
}
enum IAuthServicePath { BASE_URL, LOGIN }
extension IAuthServiceExtension on IAuthServicePath {
String get rawValue {
switch (this) {
case IAuthServicePath.LOGIN:
return '/login';
case IAuthServicePath.BASE_URL:
return 'https://reqres.in/api';
}
}
}
class AuthService extends IAuthService {
final Dio _dio = Dio();
@override
Future<AuthResponseModel?> login(AuthRequstModel model) async {
try {
Response response = await _dio.post(authPath, data: model);
print("auth service Response => $response");
if (response.statusCode == 200) {
// await UserSecureStorage.setField("token", response.data["token"]);
return AuthResponseModel.fromJson(response.data);
}
return null;
} catch (e) {
return null;
}
}
}
My Bloc => :
class AuthBloc extends Bloc<AuthEvent, AuthState> {
AuthBloc() : super(AuthInial()) {
final IAuthService _authService;
on<LoggedIn>(event, emit) async {
emit(AuthLoading());
AuthRequstModel authRequstModel =
AuthRequstModel(email: event.email, password: event.password);
final response = await _authService.login(authRequstModel); //Here i can't use it. Coz of error.
}
}
}
Thanks for helps!
Solution 1:[1]
I solved. I was forgot to add _authService to constractor.
=>
final IAuthService _authService;
AuthBloc(this._authService) : super(AuthInial()) {
on<LoggedIn>(event, emit) async {
emit(AuthLoading());
AuthRequstModel authRequstModel =
AuthRequstModel(email: event.email, password: event.password);
final response = await _authService.login(authRequstModel);
print("BLOC RESPONSE=> $response");
if (response != null) {
emit(AuthAuthenticated());
} else {
emit(AuthUnauthenticated());
}
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ugurcan Ucar |
