Flutter 将字符串转换为布尔值

Emm*_*ngo 3 string boolean dart flutter

我有一个字符串,我想将其转换为布尔值,下面是字符串的样子


String isValid = "false";

Run Code Online (Sandbox Code Playgroud)

字符串isValid可以是true或者false

有没有办法可以直接将此String isValid 转换为Boolean。我已经尝试过示例问题和解决方案,但它们只是转换硬编码的字符串,例如大多数答案只是当字符串为true

Oma*_*ury 6

在我看来,您可以根据string自己的需要创建数据类型的扩展方法,并通过各种需求检查和自定义异常来美化您所需的功能。这是一个例子:

import 'package:test/expect.dart';

void main(List<String> args) {
  String isValid = "true";

  print(isValid.toBoolean());
}

extension on String {
  bool toBoolean() {
    print(this);
    return (this.toLowerCase() == "true" || this.toLowerCase() == "1")
        ? true
        : (this.toLowerCase() == "false" || this.toLowerCase() == "0"
            ? false
            : throwsUnsupportedError);
  }
}

Run Code Online (Sandbox Code Playgroud)

在此示例中,我创建了一个isValid在 main() 方法中命名的变量,其中包含一个string值。但是,仔细看看我如何使用下面几行声明的功能将string值解析为值。boolextension

同样,您可以从任何地方访问新创建的string-extension方法toBoolean()。请记住,如果您不在toBoolean()创建扩展的同一文件中,请不要忘记导入正确的引用。

额外提示:您也可以toBoolean()这样访问,

bool alternateValidation = "true".toBoolean();
Run Code Online (Sandbox Code Playgroud)

快乐编码

  • 我不敢相信 dart 中没有开箱即用的转换原始类型的功能。 (2认同)