New flutter rules caused this ERROR: The argument type 'String?' can't be assigned to the parameter type 'String'

441 Views Asked by At

I have a code like this:

  String? _token;
  DateTime? _expiryDate;
  String? _userId;
  Timer? _authTimer;

  Future<bool> tryAutoLogin() async {
    final prefs = await SharedPreferences.getInstance();
    if (!prefs.containsKey('userData')) {
      return false;
    }
    final extractedUserData =
        json.decode(prefs.getString('userData')) as Map<String, Object>;// FIRST ERROR
    final expiryDate = DateTime.parse(extractedUserData['expiryDate']);// SECOND ERROR

    if (expiryDate.isBefore(DateTime.now())) {
      return false;
    }
    _token = extractedUserData['token']; //THIRD ERROR
    _userId = extractedUserData['userId']; // THIRD ERROR
    _expiryDate = expiryDate;
    notifyListeners();
    _autoLogout();
    return true;
  }

But it gives me these errors:

The argument type 'String?' can't be assigned to the parameter type 'String'.

The argument type 'Object?' can't be assigned to the parameter type 'String'.

A value of type 'Object?' can't be assigned to a variable of type 'String?'. Try changing the type of the variable, or casting the right-hand type to 'String?'.

I found this code from a Flutter tutorial and tried to fix the errors by adding ? or ! marks after some variable types but it seems I couldn't do that well.

EDIT: By updating this line of the code

final extractedUserData = json.decode(prefs.getString('userData')) as Map<String, Object>;

to

final extractedUserData = json.decode(prefs.getString('userData')) as Map<String, dynamic>;

The first error still exists but the other errors gone. I also tried to update the line like

final extractedUserData = json.decode(prefs!.getString('userData')) as Map<String, dynamic>;

(changed prefs to prefs!) but couldn't help, and I don't know how to fix it?

1

There are 1 best solutions below

0
On

Regarding to @ comment's I updated my code like below and it resolved all the errors:

  String? _token;
  DateTime? _expiryDate;
  String? _userId;
  Timer? _authTimer;

  Future<bool> tryAutoLogin() async {
    final prefs = await SharedPreferences.getInstance();
    if (!prefs.containsKey('userData')) {
      return false;
    }
    final extractedUserData = json.decode(prefs.getString('userData') as String)
        as Map<String, Object>;
    final expiryDate =
        DateTime.parse(extractedUserData['expiryDate'] as String);

    if (expiryDate.isBefore(DateTime.now())) {
      return false;
    }
    _token = extractedUserData['token'] as String;
    _userId = extractedUserData['userId'] as String;
    _expiryDate = expiryDate;
    notifyListeners();
    _autoLogout();
    return true;
  }