【问题标题】:Dart null-safety breaks Future<bool> anonymous method?Dart null-safety 打破 Future<bool> 匿名方法?
【发布时间】:2021-09-09 06:57:16
【问题描述】:

在迁移到零安全之前,这很有效。这是一种用户登录验证方式。

Future<bool> loginValidate() async {
    final String dir = await getDocDir(); //getting documents directory
    try {
      await File('$dir/$_userLoginString.json')
          .readAsString()
          .then((String contents) {
        final json = jsonDecode(contents) as Map<String, dynamic>;
        final user = PersonLoginJson.fromJson(json);
        if (_userPasswordString != user.password) {
          //invalid password
          return Future<bool>.value(false);
        }
      });
    } on FileSystemException {
      //invalid username
      return Future<bool>.value(false);
    } catch (e) {
      return Future<bool>.value(false);
    }
    //success
    return Future<bool>.value(true);
  }

error 在构建应用程序时出现。

我认为这与 .then() 方法中的匿名函数参数有关。

【问题讨论】:

  • 您的回调函数忽略了沿所有代码路径返回值。因此,如果不满足if 条件,它会隐式返回null,并且null 返回值是意外的。修复您的代码以沿所有代码路径返回值。另外awaitthen混用也不一致;只需使用await,这会使您的问题更加明显。

标签: flutter dart typeerror future dart-null-safety


【解决方案1】:

您需要return await 函数,还需要设置true 值才能使其工作:

return await File('$dir/$_userLoginString.json')
          .readAsString()
          .then((String contents) {
        final json = jsonDecode(contents) as Map<String, dynamic>;
        final user = PersonLoginJson.fromJson(json);
        if (_userPasswordString != user.password) {
          //invalid password
          return Future<bool>.value(false);
        }

        //Also need this code as it will return null if not set
        return Future<bool>.value(true);
      });

我认为更好:

让我们更改这段代码:

await File('$dir/$_userLoginString.json')
          .readAsString()
          .then((String contents) {
        final json = jsonDecode(contents) as Map<String, dynamic>;
        final user = PersonLoginJson.fromJson(json);
        if (_userPasswordString != user.password) {
          //invalid password
          return Future<bool>.value(false);
        }
      });

到这里:

String contents = await File('$dir/$_userLoginString.json').readAsString();
final json = jsonDecode(contents) as Map<String, dynamic>;
final user = PersonLoginJson.fromJson(json);
if (_userPasswordString != user.password) {
   //invalid password
   return Future<bool>.value(false);
}

那么现在调试你的代码会更容易。

【讨论】:

  • 这行得通,解决了。不过,在第一条语句周围仍然需要 Try - Catch 块。
【解决方案2】:
if (_userPasswordString != user.password) {
  //invalid password
  return Future<bool>.value(false);
} else {
  return Future<bool>.value(true);   // <--- here needed
}

【讨论】:

  • 这会修复它,但我有 .then() 范围之外的逻辑,它会死。
  • @Demiurge 外部逻辑是针对异常情况的,如果 api 出现异常,它仍然会存在。
猜你喜欢
  • 2023-01-03
  • 2021-08-30
  • 1970-01-01
  • 2019-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-13
相关资源
最近更新 更多