I am following a flutter tutorial uses the following codes
class Auth with ChangeNotifier {
late String _token;
late DateTime _expiryDate;
late String _userId;
late Timer _authTimer;
String get token {
if (_expiryDate != null &&
_expiryDate.isAfter(DateTime.now()) &&
_token != null) {
return _token;
}
return null;
}
Future<void> logout() async {
_token = null;
_userId = null;
_expiryDate = null;
if (_authTimer != null) {
_authTimer.cancel();
_authTimer = null;
}
notifyListeners();
final prefs = await SharedPreferences.getInstance();
// prefs.remove('userData');
prefs.clear();
}
}
But as I am using the new version of flutter it gives me the following errors:
A value of type 'Null' can't be returned from the function 'token' because it has a return type of 'String'.
Or
A value of type 'Null' can't be assigned to a variable of type 'Timer'.
Try changing the type of the variable, or casting the right-hand type to 'Timer'.
Also
A value of type 'Null' can't be assigned to a variable of type 'DateTime'.
Try changing the type of the variable, or casting the right-hand type to 'DateTime'.
I don't know how to fix this to make code run?
CodePudding user response:
Based on your declaration of method your return type is String and you returned Null instead of string. You should return empty string instead of Null.
String? get token {
if (_expiryDate != null &&
_expiryDate.isAfter(DateTime.now()) &&
_token != null) {
return _token;
}
return '';
}
for another one you should assign value based on your data type not null in every case. you should create nullable variables;
class Auth with ChangeNotifier {
String? _token;
DateTime? _expiryDate;
String? _userId;
Timer? _authTimer;
Future<void> logout() async {
_token = null;
_userId = null;
_expiryDate = null;
if (_authTimer != null) {
_authTimer?.cancel();
_authTimer = null;
}
notifyListeners();
final prefs = await SharedPreferences.getInstance();
// prefs.remove('userData');
prefs.clear();
}
CodePudding user response:
You should return the empty string '' instead of Null.
Like it says, you can't return Null.
CodePudding user response:
replace null with empty string in return type like this.
String get token {
if (_expiryDate != null &&
_expiryDate.isAfter(DateTime.now()) &&
_token != null) {
return _token;
}
return '';
}
CodePudding user response:
From memory, try changing the function type to String? get token {...} that way you're telling dart that the function can return either a String or null.