0

我有这样的代码:

  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;
  }

但它给了我这些错误:

参数类型“字符串?” 不能分配给参数类型“字符串”。

参数类型“对象?” 不能分配给参数类型“字符串”。

“对象?”类型的值 不能分配给“字符串?”类型的变量。尝试更改变量的类型,或将右手类型转换为“字符串?”。

我从 Flutter 教程中找到了这段代码,并尝试通过在某些变量类型之后添加?!标记来修复错误,但似乎我做不到。

编辑:通过更新这行代码

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

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

第一个错误仍然存​​在,但其他错误消失了。我也尝试像这样更新行

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

(更改prefsprefs!)但无济于事,我不知道如何解决?

4

1 回答 1

0

关于@comment,我更新了我的代码,如下所示,它解决了所有错误:

  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;
  }
于 2021-09-29T21:24:11.967 回答