Home > Mobile >  I need your help for an error I encounter in flutter dart
I need your help for an error I encounter in flutter dart

Time:09-27

I have an application and I created a legin and logout page... and when I click on my application's logout button, I get an error like this " Null check operator used on a null value"*and when I point to the error, it tells me [1] : https://i.stack.imgur.com/n0uJ8.pngentrez

import 'dart:async'; import 'dart:convert'; import 'dart:async'; import 'dart:convert'; import 'dart:math'; import 'package:flutter/material.dart'; import 'package:http/http.dart'; import 'package:logger/logger.dart';

import '../db/db_auth_shared_preference.dart';
import '../network/app_urls.dart';
import '../models/auth.dart';

enum Status {
notLoggedIn,
loggedIn,
authenticating,
loggedOut,

notReet,
reseted,
resetting
}

//Help display the logs
var logger = Logger();

class AuthProvider with ChangeNotifier {
Auth? _auth;

Auth get auth => _auth!;

void setAuth(Auth auth) {
_auth = auth;
notifyListeners();
}

bool isAuth() {
if (_auth == null || auth.token == '') {
return false;
}
return true;
}

// Time before the token expires
Timer? _authTimer;

DateTime? _expiryDate;
String? username;
String? password;

// Set the status of the user to Not Logged In at the start     of the app
Status _status = Status.notLoggedIn;

Status get status => _status;

// Change the status of the user
set status(Status value) {
_status = value;
notifyListeners();
}

// Log In the user
Future<Map<String, dynamic>> login(String email, String password) async {
Map<String, Object> results;

final Map<String, dynamic> loginData = {
  'email': email,
  'password': password
 };

status = Status.authenticating;
logger.d("--- Authentication ---");

try {
Response response = await post(
Uri.parse(
"${AppUrl.login}?    username=${loginData['email']}&password=${loginData['password']}"    

), );

logger.d('Login response : ${response.statusCode}');

 // The Request Succeded
 if (response.statusCode == 200) {
 final Map<String, dynamic> responseData =
 json.decode(utf8.decode(response.bodyBytes));

 var requestStatus = responseData["status"];

 if (requestStatus != 0) {
 status = Status.notLoggedIn;
 results = {'status': false, 'message': "La Connexion a échoué"};
 } else {
 // Get the status code of the request
 Map<String, dynamic> authData =    responseData["utilisateurJson"];
 logger.d(authData);

 _expiryDate = DateTime.now().add(const Duration(seconds: 3500));

  //store user shared pref
  Auth authUser = Auth.fromMap(authData,
  timeToExpire: _expiryDate,
  username: loginData['email'],
  password: loginData['password']);

  _expiryDate = authUser.expiryDate;
  logger.wtf(_expiryDate);
  //clear session data
  AuthPreferences().removeAuth();

  //store User session
  AuthPreferences().saveAuth(authUser);
  setAuth(authUser);
  status = Status.loggedIn;

  username = loginData["email"];
  password = loginData["password"];

  results = {
  'status': true,
  'message': 'Successful login',
  'auth': authUser,
  };
  autoLogOut();
  }
  } else {
  status = Status.notLoggedIn;
  results = {'status': false, 'message': 'La Connexion a échoué'};
  }
  return results;
  } catch (e) {
  logger.e(e);
  status = Status.notLoggedIn;
  results = {
  'status': false,
  'message': "La Connexion avec le serveur a échoué"
  };
  return results;
}   }

 void autoLogOut() {
 if (_authTimer != null) {
 _authTimer!.cancel();
 }
 final timeToExpiry =        _expiryDate!.difference(DateTime.now()).inSeconds;
 _authTimer = Timer(Duration(seconds: timeToExpiry),
 () async => await login(username!, password!));
 }

// Log Out the User
void logOut() {
logger.d("--- User Logging Out ---");
AuthPreferences().removeAuth();
status = Status.loggedOut;
_expiryDate = null;
_auth = null;

logger.d("--- User Logged Out ---");
 }

Future<Auth?> tryAutoLogin() async {
final authSession = await AuthPreferences().getAuth();
if (authSession == null) {
return null;
}
logger.d("The expiry time is : ${authSession.expiryDate}");
if (authSession.expiryDate.isBefore(DateTime.now())) {
login(authSession.username, authSession.password);
return authSession;
}

_expiryDate = authSession.expiryDate;
setAuth(authSession);
logger.d("SETTING THE USER");
autoLogOut();
return authSession;
}
}

CodePudding user response:

Error Explanation: Bang operator(!) means that in flutter, when you use this operator, you are completely sure that variable is not going to be null in any case.

There are two ways to resolve it -

  1. Use if conditional to confirm that variable is not null
  2. Use null-aware or if-null operator ?? like
Auth get auth => _auth ?? Auth();

Since you didn't provide any error logs; based on attached image and as your cursor on line no 29, _auth variable is null. So before using ! make sure your variable is not null.

  • Related