【问题标题】:_CastError (Null check operator used on a null value) Error_CastError(用于空值的空检查运算符)错误
【发布时间】:2022-06-19 17:32:34
【问题描述】:

我有这样的代码。但我在代码中收到_CastError (Null check operator used on a null value) 错误。

const secureStorage = FlutterSecureStorage();
 final encryprionKey = secureStorage.read(key: 'key');
 if (encryprionKey == null) {
   final key = Hive.generateSecureKey();
   await secureStorage.write(
     key: 'key',
     value: base64UrlEncode(key),
   );
 }

 final key = await secureStorage.read(key: 'key');
 final encryptionKey = base64Url.decode(key!);
 print('Encryption key: $encryptionKey');
 final encryptedBox= await Hive.openBox('vaultBox', encryptionCipher: 
 HiveAesCipher(encryptionKey));
 encryptedBox.put('secret', 'Hive is cool');
 print(encryptedBox.get('secret'));

我该如何解决?

【问题讨论】:

  • 什么是堆栈跟踪,什么是违规行?当你调用base64Url.decode(key!)时,你确定key不能是null吗?
  • @jamesdlin 密钥已经生成。也就是说,数据是预先保存的。
  • 可能key没有生成/保存,尝试打印看看是不是== null
  • if (encryprionKey == null) { 这一行,警告是什么?
  • @Belinda G. Freitas The operand can't be null, so the condition is always false. Try removing the condition, an enclosing condition, or the whole conditional statement.

标签: android flutter dart


【解决方案1】:

final encryprionKey = secureStorage.read(key: 'key'); 忽略await secureStorage.read 的结果。返回的Future 本身永远不会是null,因此if (encryprionKey == null) 检查永远不会为真,什么都没有写入,第二个secureStorage.read 调用(awaited)将回复null

这就是 Dart 分析器警告您 if (encryprionKey == null) 条件始终为假的原因。启用unawaited_futures lint 会产生额外的(也许更清楚)警告。

secureStorage.read 的两次调用没有单独的变量也会将此视为编译错误:

  const secureStorage = FlutterSecureStorage();
  var encryprionKey = secureStorage.read(key: 'key');
  if (encryprionKey == null) {
    final key = Hive.generateSecureKey();
    await secureStorage.write(
      key: 'key',
      value: base64UrlEncode(key),
    );
  }

  // This line would have generated a TypeError.
  encryprionKey = await secureStorage.read(key: 'key'); 

在这种情况下,最好重新分配encryprionKey(原文如此)变量,而不是使用单独的key 变量使其final。用不同的变量来表示同一事物会更加混乱并且容易出错。

【讨论】:

    猜你喜欢
    • 2022-08-06
    • 2022-01-13
    • 2021-06-13
    • 2021-12-15
    • 2021-10-22
    • 1970-01-01
    • 2022-06-27
    • 2021-11-04
    • 1970-01-01
    相关资源
    最近更新 更多